1、什么是栈?
C++ Stacks(堆栈)
(1)C++ Stack(堆栈) 是一个容器类的改编,为程序员提供了堆栈的全部功能,——也就是说实现了一个先进后出(FILO)的数据结构。
(2)STL 栈 (
std::stack
) 是一种后进先出 (Last In, First Out) 的容器适配器,仅支持查询或删除最后一个加入的元素(栈顶元素),不支持随机访问,且为了保证数据的严格有序性,不支持迭代器。
2、头文件
#include <stack>
3、定义
std::stack<TypeName> s; // 使用默认底层容器 deque,数据类型为 TypeName
std::stack<TypeName, Container> s; // 使用 Container 作为底层容器
std::stack<TypeName> s2(s1); // 将 s1 复制一份用于构造 s2
4、相关操作(函数)
操作 | 比较和分配堆栈 |
empty() | 堆栈为空则返回真 |
pop() | 移除栈顶元素 |
push() | 在栈顶增加元素 |
size() | 返回栈中元素数目 |
top() | 返回栈顶元素 |
5、代码示例:
#include<iostream>
#include<stack>
using namespace std;
int main()
{
stack<string> s;
string ch[5] = { "我","喝","牛","奶"};
for (int i = 0; i < 5; i++)
s.push(ch[i]);
int n = s.size();
for (int i = 0; i < n; i++)
{
cout<<s.top()<<' ';
s.pop();
}
return 0;
}
6、运行结果
入栈内容:
出栈内容: