C++ STL容器: 栈
栈是一种具有后进先出(LIFO)特性的数据结构,C++ STL中提供了stack容器来实现栈的功能。在使用stack容器时,需要包含头文件。
以下是一个简单的示例代码,用于演示如何使用stack容器:
#include <iostream>
#include <stack>
int main() {
// 创建一个空栈
std::stack<int> s;
// 将元素压入栈中
s.push(1);
s.push(2);
s.push(3);
// 访问栈顶元素并弹出
std::cout << "栈顶元素:" << s.top() << std::endl;
s.pop();
// 判断栈是否为空
if (s.empty()) {
std::cout << "栈为空" << std::endl;
} else {
std::cout << "栈不为空" << std::endl;
}
// 获取栈中元素数量
std::cout << "栈中元素数量:" << s.size() << std::e