STL stack
stack 栈适配器是一种单端开口的容器,实际上该容器模拟的就是栈存储结构,即无论是向里存数据还是从中取数据,都只能从这一个开口实现操作。
如图所示,stack 适配器的开头端通常称为栈顶。由于数据的存和取只能从栈顶处进行操作,因此对于存取数据,stack 适配器有这样的特性,即每次只能访问适配器中位于最顶端的元素,也只有移除 stack 顶部的元素之后,才能访问位于栈中的元素。
创建stack容器
//方法一
std::stack<int> values;
//方法二
//使用vector、deque 和 list基础容器的 stack 适配器
std::stack<std::string, std::list<int>> values;
//方法三
//使用一个基础容器来初始化 stack 适配器
std::list<int> values {1, 2, 3};
std::stack<int,std::list<int>> my_stack (values);
//注意,初始化后的 my_stack 适配器中,栈顶元素为 3,而不是 1
//方法四
//还可以用一个 stack 适配器来初始化另一个 stack 适配器
std::list<int> values{ 1, 2, 3 };
std::stack<int, std::list<int>> my_stack1(values);
std::stack<int, std::list<int>> my_stack=my_stack1;
//std::stack<int, std::list<int>> my_stack(my_stack1);
stack容器适配器支持的成员函数
成员函数 | 功能 |
---|---|
empty() | 当 stack 栈中没有元素时,该成员函数返回 true;反之,返回 false。 |
size() | 返回 stack 栈中存储元素的个数。 |
top() | 返回一个栈顶元素的引用,类型为 T&。如果栈为空,程序会报错。 |
push(const T& val) | 先复制 val,再将 val 副本压入栈顶。这是通过调用底层容器的 push_back() 函数完成的。 |
push(T&& obj) | 以移动元素的方式将其压入栈顶。这是通过调用底层容器的有右值引用参数的 push_back() 函数完成的。 |
pop() | 弹出栈顶元素。 |
emplace(arg…) | arg… 可以是一个参数,也可以是多个参数,但它们都只用于构造一个对象,并在栈顶直接生成该对象,作为新的栈顶元素。 |
swap(stack & other_stack) | 将两个 stack 适配器中的元素进行互换,需要注意的是,进行互换的 2 个 stack 适配器中存储的元素类型以及底层采用的基础容器类型,都必须相同。 |
示范代码:
#include <iostream>
#include <stack>
#include <list>
using namespace std;
int main(){
//构建stack容器
list<int> l{1,2,3};
stack<int,list<int>> myStack(l);
//输出元素个数
cout<<"元素个数:"<<myStack.size()<<endl;
//将存储的元素以此弹栈
while(!myStack.empty()){
cout<<myStack.top()<<endl;
myStack.pop();
}
return 0;
}
运行结果: