Chinaunix首页 | 论坛 | 博客
  • 博客访问: 7650578
  • 博文数量: 961
  • 博客积分: 15795
  • 博客等级: 上将
  • 技术积分: 16612
  • 用 户 组: 普通用户
  • 注册时间: 2010-08-07 14:23
文章分类

全部博文(961)

文章存档

2016年(1)

2015年(61)

2014年(41)

2013年(51)

2012年(235)

2011年(391)

2010年(181)

分类: C/C++

2011-08-12 17:01:49

《C++Primer4th第四版中文版》

除了顺序容器,标准库还提供了三种顺序容器适配器:queuepriority_queue stack

适配器通用的操作和类型

size_type 一种类型,足以存储此适配器类型最大对象的长度 value_type 元素类型

container_type 基础容器的类型,适配器在此容器类型上实现

A a; 创建一个新空适配器,命名为 a

A a(c); 创建一个名为 a 的新适配器,初始化为容器 c 的副本

关系操作符 所有适配器都支持全部关系操作符:== != < <= >>=

使用适配器时,必须包含相关的头文件:

#include     // stack adaptor

#include     // both queue and priority_queue adaptors

 

栈容器适配器支持的操作

s.empty() 如果栈为空,则返回 true,否则返回 stack

s.size() 返回栈中元素的个数

s.pop() 删除栈顶元素的值,但不返回其值

s.top() 返回栈顶元素的值,但不删除该元素

s.push(item) 在栈顶压入新元素

#include

#include

using namespace std;

 

int main(void)

{

    const stack<int>::size_type stk_size = 10;

     stack<int> intStack; // empty stack

     // fill up the stack

     int ix = 0;

     while (intStack.size() != stk_size)

         // use postfix increment; want to push old value onto intStack

         intStack.push(ix++); // intStack holds 0...9 inclusive

 

     int error_cnt = 0;

     // look at each value and pop it off the stack

     while (intStack.empty() == false) {

         int value = intStack.top();

         // read the top element of the stack

         if (value != --ix) {

             cerr << "oops! expected " << ix

                  << " received " << value << endl;

             ++error_cnt; }

         intStack.pop(); // pop the top element, and repeat

     }

     cout << "Our program ran with "

          << error_cnt << " errors!" << endl;

   

    return 0;

}

 

队列和优先级队列支持的操作

q.empty() 如果队列为空,则返回 true,否则返回 false

q.size() 返回队列中元素的个数

q.pop() 删除队首元素,但不返回其值

q.front()  返回队首元素的值,但不删除该元素 该操作只适用于队列

q.back()  返回队尾元素的值,但不删除该元素 该操作只适用于队列

q.top()  返回具有最高优先级的元素值,但不删除该元素 该操作只适用于优先级队列

q.push(item) 对于 queue,在队尾压入一个新元素,对于 priority_quue,在基于优先级的适当位置插入新元素

阅读(1918) | 评论(0) | 转发(2) |
0

上一篇:标准库 bitset

下一篇:C++STL学习经典

给主人留下些什么吧!~~