stack

概念

STL(标准模板库)中的 stack 是 C++ 中的栈容器。实现了栈的基本功能。

主要特点

  1. **先进后出 (LIFO)**:stack 是一种先进后出(LIFO)数据结构,元素的插入和删除都在同一端进行,即栈顶。
  2. 底层实现stack 通常使用双端队列(deque)或链表作为底层实现。
  3. 限制操作:只能访问栈顶元素(top())、进行入栈(push())和出栈(pop())操作。

基本用法

1. 创建和初始化

1
2
3
4
5
6
7
8
9
10
11
#include <stack>
#include <iostream>

using namespace std;

int main() {
stack<int> s; // 创建一个空的 stack

return 0;
}

2. 元素操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <stack>
#include <iostream>

using namespace std;

int main() {
stack<int> s;

// 入栈
s.push(1); // 在栈顶插入 1
s.push(2); // 在栈顶插入 2
s.push(3); // 在栈顶插入 3

// 访问栈顶元素
cout << "Top: " << s.top() << endl; // 输出栈顶元素 3

// 出栈
s.pop(); // 删除栈顶元素 3

// 访问修改后的栈顶元素
cout << "Top: " << s.top() << endl; // 输出新的栈顶元素 2

return 0;
}

3. 检查栈的状态

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <stack>
#include <iostream>

using namespace std;

int main() {
stack<int> s;

// 检查栈是否为空
if (s.empty()) {
cout << "Stack is empty." << endl;
}

// 入栈
s.push(1);

// 检查栈大小
cout << "Size: " << s.size() << endl; // 输出栈的大小

return 0;
}

常用成员函数

  • 元素操作

    • push(const T& value):在栈顶插入一个元素。
    • pop():移除栈顶元素。
    • top():返回栈顶元素的引用。
  • 状态检查

    • empty():检查栈是否为空,返回布尔值。
    • size():返回栈中元素的数量。

stack
http://pikachuxpf.github.io/posts/41a87b6a/
作者
Pikachu_fpx
发布于
2024年7月23日
许可协议