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中,然后再显示输入的单词。
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int main()
{
    stack<string> words;
    string str;
    cout<<"Enter some words(Ctrl + Z to end):"<<endl;
    while(cin >> str)
    {
        words.push(str);
    }
    while(words.empty() == false)
    {
        cout<<words.top()<<endl;
        words.pop();
    }
    return 0;
}


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

using namespace std;

int main()
{
	stack<char> sta;
	string str;

	cin>>str;

	string::iterator iter = str.begin();

	while(iter != str.end())
	{
		if(*iter != ')')
			sta.push(*iter);
		else	//*iter == ')'
		{
			while(sta.top() != '(' && !sta.empty())
			{
				sta.pop();
			}

			if (sta.empty())
			{
				cout<<"No '(' matched!"<<endl;
			}
			else //*iter == '('
			{
				sta.pop();
				sta.push('@');
			}
		}

		++iter;
	}

	while(!sta.empty())
	{
		cout<<sta.top()<<endl;
		sta.pop();
	}

	return 0;
}



  • 8
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值