c++ STL容器适配器

时间:2023-03-09 00:27:26
c++  STL容器适配器

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

    标准库提供了三种顺序容器适配器: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中,然后再显示输入的单词。
  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. }
c++  STL容器适配器

2、使用stack处理带圆括号的表达式。遇到左括号时,将其标记下来。遇到右括号时,弹出stack中两括号之间的元素(包括括号),并压入一个"@"表示其已被替换。

    1. #include <iostream>
    2. #include <stack>
    3. #include <string>
    4. using namespace std;
    5. int main()
    6. {
    7. stack<char> sta;
    8. string str;
    9. cin>>str;
    10. string::iterator iter = str.begin();
    11. while(iter != str.end())
    12. {
    13. if(*iter != ')')
    14. sta.push(*iter);
    15. else    //*iter == ')'
    16. {
    17. while(sta.top() != '(' && !sta.empty())
    18. {
    19. sta.pop();
    20. }
    21. if (sta.empty())
    22. {
    23. cout<<"No '(' matched!"<<endl;
    24. }
    25. else //*iter == '('
    26. {
    27. sta.pop();
    28. sta.push('@');
    29. }
    30. }
    31. ++iter;
    32. }
    33. while(!sta.empty())
    34. {
    35. cout<<sta.top()<<endl;
    36. sta.pop();
    37. }
    38. return 0;
    39. }

c++  STL容器适配器