C++ 容器适配器详解:stack、queue 与 priority_queue

目录

C++ 容器适配器详解:stack、queue 与 priority_queue

引言

1. stack(栈)

1.1 stack 简介

1.2 stack 的基本操作

1.3 有关栈的几个oj题(原题查力扣or牛客)

栈的弹出压入序列验证

逆波兰表达式求值

1.4 stack 的模拟实现

2. queue(队列)

2.1 queue 简介

2.2 queue 的基本操作

2.3 queue 的模拟实现

3. priority_queue(优先队列)

3.1 priority_queue 简介

3.2 priority_queue 的基本操作

3.3 自定义类型在 priority_queue 中的使用

3.4 priority_queue 的模拟实现

4. 容器适配器与底层容器

4.1 什么是容器适配器

4.2 为什么选择 deque 作为默认底层容器

4.3 deque 的简单介绍

5. 总结


C++ 容器适配器详解:stack、queue 与 priority_queue

引言

在 C++ 标准模板库(STL)中,容器适配器是一类特殊的容器,它们基于现有的容器类进行封装,提供特定的接口来满足不同的数据结构需求。本文将深入探讨三种主要的容器适配器:stack(栈)、queue(队列)和 priority_queue(优先队列),包括它们的使用方法、实现原理以及底层容器选择。

1. stack(栈)

1.1 stack 简介

栈是一种后进先出(LIFO)的数据结构,只允许在容器的一端进行插入和删除操作。在 C++ 中,std::stack 是一个容器适配器,它基于其他容器(如 deque 或 vector)实现。

#include <stack>
#include <vector>

std::stack<int> s1; // 默认使用 deque 作为底层容器
std::stack<int, std::vector<int>> s2; // 使用 vector 作为底层容器

1.2 stack 的基本操作

  • push(): 将元素压入栈顶
  • pop(): 弹出栈顶元素
  • top(): 访问栈顶元素
  • empty(): 检查栈是否为空
  • size(): 返回栈中元素数量

1.3 有关栈的几个oj题(原题查力扣or牛客)

栈的弹出压入序列验证
bool IsPopOrder(vector<int> pushV, vector<int> popV) {
    if(pushV.size() != popV.size())
        return false;
    
    int outIdx = 0;
    int inIdx = 0;
    stack<int> s;
    
    while(outIdx < popV.size()) {
        while(s.empty() || s.top() != popV[outIdx]) {
            if(inIdx < pushV.size())
                s.push(pushV[inIdx++]);
            else
                return false;
        }
        s.pop();
        outIdx++;
    }
    return true;
}
逆波兰表达式求值
int evalRPN(vector<string>& tokens) {
    stack<int> s;
    for (const auto& token : tokens) {
        if (token == "+" || token == "-" || token == "*" || token == "/") {
            int b = s.top(); s.pop();
            int a = s.top(); s.pop();
            if (token == "+") s.push(a + b);
            else if (token == "-") s.push(a - b);
            else if (token == "*") s.push(a * b);
            else s.push(a / b);
        } else {
            s.push(stoi(token));
        }
    }
    return s.top();
}

1.4 stack 的模拟实现

#include <vector>

namespace bite {
template<class T, class Container = std::vector<T>>
class stack {
public:
    void push(const T& x) { _c.push_back(x); }
    void pop() { _c.pop_back(); }
    T& top() { return _c.b
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值