C++中的容器适配器:stack、queue、priority_queue

一、定义

适配器adaptor是标准库的一个通用概念。容器、迭代器、函数都有适配器。

适配器可以使得某种事物行为,看起来像另外一种事物一样。

一个容器适配器,接受一种已有的容器类型,使表现看起来像是一种不同的类型。

举例:

stack<int> stk(deq); // 从deque拷贝元素到stack


函数适配器bind

迭代器适配器

二、操作和类型

通用操作包括:
在这里插入图片描述

1. 栈stack适配器

在这里插入图片描述

2. queue适配器

在这里插入图片描述
在这里插入图片描述注意:

  1. 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"
}

输出结果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值