C++中的栈

C++ 中的栈(Stack)

栈是一种遵循后进先出(LIFO)原则的数据结构,C++ 标准库(STL)提供了 std::stack 容器适配器来实现栈的功能。

基本用法

需要包含头文件 <stack>,使用 std::stack 定义栈对象:

#include <stack>
std::stack<int> s; // 定义一个存储整型的栈

常用操作
  1. 压栈(Push):将元素添加到栈顶。

    s.push(10); // 栈顶元素变为 10
    s.push(20); // 栈顶元素变为 20
    

  2. 弹栈(Pop):移除栈顶元素(不返回其值)。

    s.pop(); // 移除 20,栈顶元素变为 10
    

  3. 访问栈顶(Top):获取栈顶元素的值(不移除)。

    int top_val = s.top(); // 获取 10
    

  4. 检查栈是否为空

    bool is_empty = s.empty(); // 返回 false(栈非空)
    

  5. 获取栈的大小

    size_t size = s.size(); // 返回当前元素数量
    

底层容器

std::stack 默认使用 std::deque 作为底层容器,但可以指定其他容器(如 std::vectorstd::list):

std::stack<int, std::vector<int>> s_vec; // 使用 vector 作为底层容器

注意事项
  • 调用 top()pop() 前需确保栈非空,否则可能引发未定义行为。
  • 栈不支持随机访问或迭代器操作。
示例代码
#include <iostream>
#include <stack>

int main() {
    std::stack<int> s;
    s.push(1);
    s.push(2);
    s.push(3);

    while (!s.empty()) {
        std::cout << s.top() << " "; // 输出 3 2 1
        s.pop();
    }
    return 0;
}

手动实现栈

若需自定义栈,可以通过数组或链表实现。以下是基于数组的简化示例:

class CustomStack {
private:
    int* data;
    int capacity;
    int top_idx;

public:
    CustomStack(int size) : capacity(size), top_idx(-1) {
        data = new int[capacity];
    }

    ~CustomStack() { delete[] data; }

    void push(int val) {
        if (top_idx < capacity - 1) data[++top_idx] = val;
    }

    void pop() {
        if (top_idx >= 0) --top_idx;
    }

    int top() { return data[top_idx]; }

    bool empty() { return top_idx == -1; }
};

应用场景

  • 函数调用栈(递归调用)
  • 表达式求值(如括号匹配)
  • 撤销操作(如编辑器中的 Ctrl+Z)

如需更高级功能(如线程安全),可考虑使用第三方库或自行扩展实现。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值