如何使用queue?

此范例demo如何使用STL的queue container,要将数据加进queue时,只要用q.push(item)即可,但要取出数据时,并不是用q.pop(),而是用q.front()取出最前面的数据,q.pop()则是将最前面的数据取出queue,其回传值为void。

 

/**//* 
(C) OOMusou 2006 
http://oomusou.cnblogs.com 
Filename    : Queue.cpp 
Compiler    : Visual C++ 8.0 
Description : Demo how to use queue 
Release     : 11/25/2006 
*/
 
#include 
<conio.h> // for _getch() 
#include <queue> // for std::queue 
#include <iostream> 
 
std::queue
<char> charQueue; 

int main() 
char c; 
while(c = _getch()) 
switch(c) 
case '1'
case '2'
case '3'
case '4'
        charQueue.push(c); 
break
case 'q'
goto stop; 
break
    }
 
  }
 

  stop: 
while(!charQueue.empty()) 
    std::cout 
<< charQueue.front() << std::endl; 
    charQueue.pop(); 
  }
 

return 0
}


      在以前Turbo C时代,在<stdio.h>中有getch()可抓取输入的char值,且不在屏幕上出现,但Visual C++已经无getch()了,取而代之的是<conio.h>的_getch(),据MSDN Library的ms-help://MS.MSDNQTR.v80.en/MS.MSDN.v80/MS.VisualStudio.v80.en/dv_vccrt/html/d3a0b744-d63c-4f71-960e-24e619dccd01.htm 所述,_getch()为ISO C++所定义的,但我在Linux的gcc并无法使用_getch()。
      此范例还demo了C++独特的switch fall through写法,这种写法在C#并不允许,理由是很多人因为在switch中少写了break而造成程序错误,所以强制switch中一定要使用break,但C++则允许不写break,不写break的优点是可以多个case共享一个叙述,如19行到22行,若使用if搭配||当然可以写出来,但程序的可读性差很多。第26行虽然动了goto,但goto只要是往下跳则还可接受,不太影响程序阅读,但goto往上跳则严格禁止。
Reference
C++标准链接库 中文版 P.444 ~ P.447, Nicolai M. Josuttis 着,侯捷/孟岩 译, Addison Wiseley/碁峰出版社

posted @ 2009-07-23 08:32  回忆1919  阅读(593)  评论(0编辑  收藏  举报