C++容器适配器


一、标准库顺序容器适配器的种类


    标准库提供了三种顺序容器适配器:queue(FIFO队列)、priority_queue(优先级队列)、stack(栈)

二、什么是容器适配器

    ”适配器是使一种事物的行为类似于另外一种事物行为的一种机制”,适配器对容器进行包装,使其表现出另外一种行为。例如,stack<int, vector<int> >实现了栈的功能,但其内部 使用顺序容器vector<int>来存储数据 。(相当于是vector<int>表现出了栈的行为)。

三、容器适配器

    要使用适配器,需要加入一下头文件:
    #include <stack>          //stack
    #include<queue>         //queue、priority_queue
种类 默认顺序容器 可用顺序容器 说明
stack deque vector、list、deque
queue deque list、deque 基础容器必须提供push_front()运算
priority_queue vector vector、deque 基础容器必须提供随机访问功能

四、定义适配器

1、初始化
         stack<int> stk(dep);

2、覆盖默认容器类型
        stack<int,vector<int> > stk;

五、容器适配器的使用


1、 下面的程序读入一系列单词存储在stack中,然后再显示输入的单词。
[cpp]  view plain  copy
  1. #include <iostream>  
  2. #include <stack>  
  3. #include <string>  
  4. using namespace std;  
  5. int main()  
  6. {  
  7.     stack<string> words;  
  8.     string str;  
  9.     cout<<"Enter some words(Ctrl + Z to end):"<<endl;  
  10.     while(cin >> str)  
  11.     {  
  12.         words.push(str);  
  13.     }  
  14.     while(words.empty() == false)  
  15.     {  
  16.         cout<<words.top()<<endl;  
  17.         words.pop();  
  18.     }  
  19.     return 0;  
  20. }  


2、使用stack处理带圆括号的表达式。遇到左括号时,将其标记下来。遇到右括号时,弹出stack中两括号之间的元素(包括括号),并压入一个"@"表示其已被替换。
[cpp]  view plain  copy
  1. #include <iostream>  
  2. #include <stack>  
  3. #include <string>  
  4.   
  5. using namespace std;  
  6.   
  7. int main()  
  8. {  
  9.     stack<char> sta;  
  10.     string str;  
  11.   
  12.     cin>>str;  
  13.   
  14.     string::iterator iter = str.begin();  
  15.   
  16.     while(iter != str.end())  
  17.     {  
  18.         if(*iter != ')')  
  19.             sta.push(*iter);  
  20.         else    //*iter == ')'  
  21.         {  
  22.             while(sta.top() != '(' && !sta.empty())  
  23.             {  
  24.                 sta.pop();  
  25.             }  
  26.   
  27.             if (sta.empty())  
  28.             {  
  29.                 cout<<"No '(' matched!"<<endl;  
  30.             }  
  31.             else //*iter == '('  
  32.             {  
  33.                 sta.pop();  
  34.                 sta.push('@');  
  35.             }  
  36.         }  
  37.   
  38.         ++iter;  
  39.     }  
  40.   
  41.     while(!sta.empty())  
  42.     {  
  43.         cout<<sta.top()<<endl;  
  44.         sta.pop();  
  45.     }  
  46.   
  47.     return 0;  
  48. }  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值