“适配器本质上是一种机制,能使某种事物的行为看起来想另外一种事物一样。一个容器适配器接受一种已有的容器类型,使其行为看起来像一种不同的类型。”
我的理解是,适配器就是类似转换线,我们无需重新写一个新的容器,而只需利用适配器,就可以在原来容器的基础上进行一些操作。但那为什么不直接用原来的容器呢?我想可能是因为STL中的容器是通用模板十分强大,但我们在某些应用中并不需要,有时只需其中的一部分功能,这时用适配器则效率更高也不怕出错。
stack是后进先出,要求push_back、pop_back和back操作。
queue是先进先出,要求back、push_back、front和push_front操作。
此处给出stack的实例。
题目:将一个表达式中的括号及括号内的内容换为你所想要的值,并输出最终表达式。
#include<iostream> //将括号及其内容换为#
#include<vector>
#include<string>
#include<stack>
using namespace std;
int main()
{
string str = "This is (Mooophy(awesome)((((wooooooooo))))) and (ocxs) over";
stack<char> s;
char replace = '#';
int count = 0;
for (auto &i : str)
{
s.push(i);
if (i == '(')
++count;
if (count && i == ')')
{
while (s.top() != '(')
s.pop();
s.pop();
s.push(replace);
--count;
}
}
string output;
for (; !s.empty(); s.pop())
output.insert(output.begin(), s.top());
cout << output << endl;
system("pause");
}