简介
Stack是一种容器适配器,专门为元素后进先出操作而设计。元素只能在容器的一端插入和删除。
Stack被作为容器适配器而实现,它是一个使用指定容器类作为其潜在容器存储元素,并提供一组操作函数对容器中的元素进行操作的类。
潜在容器可以是任何的标准容器或一些被特别设计的容器类。但它们必须满足以下几个操作:
Ø back()
Ø push_back()
Ø pop_back()
其中标准容器中的vector、deque和list都能满足这些要求。默认情况下,如果没有特别指明那个容器类作为stack类潜在容器,deque将作为其默认的实例化容器类。
成员函数
stack::stack()
构造一个stack容器适配器对象。
stack::empty()
判断容器是否为空,如果是返回true,否则返回false。
stack::size()
返回statck中元素的个数。
stack::top()
返回一个指向栈顶的引用。
stack::push()
向栈顶插入一个元素。
stack::emplace()
向栈顶插入一个元素,元素通过其构造函数构造。
stack::pop()
从栈顶移除一个元素。
stack::swap()
交换两个栈的元素。
示例程序
#include <iostream>
#include <stack>
#include <deque>
#include <vector>
using namespace std;
int main(void)
{
deque<int> deq(3, 10);
vector<int> vec(3, 20);
// stack::stack()
stack<int> first;
stack<int> second(deq);
stack<int, vector<int>> third;
stack<int, vector<int>> fourth(vec);
// stack::empty()
if(!second.empty()){
cout << "Stack is not empty." << endl;
}else{
cout << "Stack is empty." << endl;
}
// stack::size()
cout << "The size of fourth is " << fourth.size();
cout << endl;
// stack::top()
cout << "The top element is " << second.top() << endl;
// stack::push()
second.push(20);
cout << "The top element is " << second.top() << endl;
//stack::emplace()
second.emplace(30);
cout << "The top element is " << second.top() << endl;
// stack::pop()
second.pop();
cout << "The top element is " << second.top() << endl;
// stack::swap()
second.swap(first);
cout << "The size of first : " << first.size() << endl;
cout << "The size of second : " << second.size() << endl;
return 0;
}