博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
(原創) 如何使用queue? (C/C++) (STL)
阅读量:6922 次
发布时间:2019-06-27

本文共 1277 字,大约阅读时间需要 4 分钟。

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

 1
ExpandedBlockStart.gif
ContractedBlock.gif
/**/
/* 
 2InBlock.gif(C) OOMusou 2006 http://oomusou.cnblogs.com
 3InBlock.gif
 4InBlock.gifFilename    : Queue.cpp
 5InBlock.gifCompiler    : Visual C++ 8.0
 6InBlock.gifDescription : Demo how to use queue
 7InBlock.gifRelease     : 11/25/2006
 8ExpandedBlockEnd.gif*/
 9
None.gif#include 
<
conio.h
>
 
//
 for _getch()
10
None.gif
#include 
<
queue
>
   
//
 for std::queue
11
None.gif
#include 
<
iostream
>
12
None.gif
13
None.gifstd::queue
<
char
>
 charQueue;
14
None.gif
15
ExpandedBlockStart.gifContractedBlock.gif
int
 main() 
dot.gif
{
16InBlock.gif  char c;
17ExpandedSubBlockStart.gifContractedSubBlock.gif  while(c = _getch()) dot.gif{
18ExpandedSubBlockStart.gifContractedSubBlock.gif    switch(c) dot.gif{
19InBlock.gif      case '1':
20InBlock.gif      case '2':
21InBlock.gif      case '3':
22InBlock.gif      case '4':
23InBlock.gif        charQueue.push(c);
24InBlock.gif        break;
25InBlock.gif      case 'q':
26InBlock.gif        goto stop;
27InBlock.gif        break;
28ExpandedSubBlockEnd.gif    }
29ExpandedSubBlockEnd.gif  }
30InBlock.gif
31InBlock.gif  stop:
32ExpandedSubBlockStart.gifContractedSubBlock.gif  while(!charQueue.empty()) dot.gif{
33InBlock.gif    std::cout << charQueue.front() << std::endl;
34InBlock.gif    charQueue.pop();
35ExpandedSubBlockEnd.gif  }
36InBlock.gif
37InBlock.gif  return 0;
38ExpandedBlockEnd.gif}
在以前Turbo C时代,在<stdio.h>中有getch()可抓取输入的char值,且不在屏幕上出现,但Visual C++已经无getch()了,取而代之的是<conio.h>的_getch(),据MSDN Library的  所述,_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/碁峰出版社

转载地址:http://etkjl.baihongyu.com/

你可能感兴趣的文章
How do I duplicate a resource reference in code behind in WPF?如何在WPF后台代码中中复制引用的资源?...
查看>>
vc写的dll被mingw的g++编译引用
查看>>
整个ssd的网络和multibox_loss_layer
查看>>
js中数组如何使用
查看>>
centos7 常用工具包安装
查看>>
C BIN加密
查看>>
【EJB学习笔记】——EJB开发环境搭建(Eclipse集成JBoss)
查看>>
js cookie库
查看>>
使用 Chrome 开发者工具进行 JavaScript 问题定位与调试
查看>>
TP-admin即基于ThinkPHP5拿来即用高性能后台管理系统
查看>>
理解String的compareTo()方法返回值
查看>>
如何将xml转为python中的字典
查看>>
在WCF服务端的web.config中增加如下设置,具体的错误会记录在.svclog文件中
查看>>
PHP 手机短信验证码 laravel 实现流程
查看>>
离线安装Cloudera Manager 5和CDH5(最新版5.9.3) 完全教程(二)基础环境安装
查看>>
iOS 代码混淆
查看>>
错误整理:No plugin found for prefix 'jetty' in the current project and in the plugin groups
查看>>
Git 修改远端仓库地址
查看>>
浅谈分布式数据库
查看>>
Android 应用防止被二次打包指南
查看>>