一、定义
适配器adaptor
是标准库的一个通用概念。容器、迭代器、函数都有适配器。
适配器可以使得某种事物行为,看起来像另外一种事物一样。
一个容器适配器,接受一种已有的容器类型,使表现看起来像是一种不同的类型。
举例:
stack<int> stk(deq); // 从deque拷贝元素到stack
附:
函数适配器bind
二、操作和类型
通用操作包括:
1. 栈stack适配器
2. queue适配器
注意:
- priority_queue保证优先级别最高的在queue的最前面。在默认情况下,使用
<
运算符来确定相对优先级。我们可以重载运算符实现自定义排序。
三、实例
题目:
使用stack处理带括号的表达式。
解答:
#include <stack>
using std::stack;
#include <string>
using std::string;
#include <iostream>
using std::cout;
using std::endl;
int main()
{
auto& expr = "This is (allenhsu(awesome)((((wooooooooo))))) and (ocxs) over";
auto repl = '#';
auto seen = 0;
stack<char> stk;
for (auto c : expr) {
stk.push(c);
if (c == '(') ++seen; // open
if (seen && c == ')') { // pop elements down to the stack
while (stk.top() != '(') stk.pop();
stk.pop(); // including the open parenthesis
stk.push(repl); // push a value indicate it was replaced
--seen; // close
}
}
// Test
string output;
for (; !stk.empty(); stk.pop()) output.insert(output.begin(), stk.top());
cout << output << endl; // "This is # and # over"
}
输出结果: