C++中stack函数的用法示例
C++中stack函数的用法示例
std::stack
是C++标准模板库(STL)中的一个容器适配器,它提供了后进先出(LIFO)的数据结构。以下是stack的一些常用函数及其用法示例:
1. 基本操作
#include <iostream> #include <stack> int main() { // 创建一个整数栈 std::stack<int> s; // push() - 将元素压入栈顶 s.push(10); s.push(20); s.push(30); // top() - 访问栈顶元素 std::cout << "栈顶元素: " << s.top() << std::endl; // 输出 30 // pop() - 移除栈顶元素 s.pop(); std::cout << "弹出后栈顶元素: " << s.top() << std::endl; // 输出 20 return 0; }
2. 大小相关操作
#include <iostream> #include <stack> int main() { std::stack<std::string> names; names.push("Alice"); names.push("Bob"); names.push("Charlie"); // size() - 返回栈中元素数量 std::cout << "栈大小: " << names.size() << std::endl; // 输出 3 //