stacks are implemented as containers adaptors, which are classes that use an encapsulated object of a specific container class as its underlying container, providing a specific set of member functions to access its elements. Elements are pushed/popped from the "back" of the specific container, which is known as the top of the stack.
c++中stack是建立在底层容器基础上的。
The underlying container may be any of the standard container class templates or some other specifically designed container class. The only requirement is that it supports the following operations:
back()// access the last elment
push_back()
pop_back()
实现C++ STL,栈有两个参数。
|
参数示意:
- T: 元素类型
- Container: 被用于存储和访问元素的的类型
- Therefore, the standard container class templates vector, deque and list can be used. By default, if no container class is specified for a particular stack class, the standard container class template deque is used.
- 如果不指定第2个参数(容器类型,就为deque)
构造函数
explicit stack ( const Container& ctnr = Container() );
Constructs a stack container adaptor object.
A container adaptor keeps a container object as data. This container object is a copy of the argument passed to the constructor, if any, otherwise it is an empty container.
// constructing stacks #include <iostream> #include <vector> #include <deque> #include <stack> using namespace std; int main () { deque<int> mydeque (3,100); // deque with 3 elements vector<int> myvector (2,200); // vector with 2 elements stack<int> first; // empty stack stack<int> second (mydeque); // stack initialized to copy of deque stack<int,vector<int> > third; // empty stack using vector stack<int,vector<int> > fourth (myvector); cout << "size of first: " << (int) first.size() << endl; cout << "size of second: " << (int) second.size() << endl; cout << "size of third: " << (int) third.size() << endl; cout << "size of fourth: " << (int) fourth.size() << endl; return 0; }
注意,当容器类型不是默认的deque时,一定要指定容器类型,否则报错。
基本操作:
void push ( const T& x );
void pop ( );
移去顶元素,The value of this element can be retrieved before being popped by calling member stack::top.
// stack::push/pop #include <iostream> #include <stack> using namespace std; int main () { stack<int> mystack; for (int i=0; i<5; ++i) mystack.push(i); cout << "Popping out elements..."; while (!mystack.empty()) { cout << " " << mystack.top(); mystack.pop(); } cout << endl; return 0; }
输出: 4,3 ,2,1,0
value_type& top ( ); const value_type& top ( ) const;
Returns a reference to the next element in the stack. Since stacks are last-in first-out containers this is also the last element pushed into the stack.
// stack::top #include <iostream> #include <stack> using namespace std; int main () { stack<int> mystack; mystack.push(10); mystack.push(20); mystack.top() -= 5; cout << "mystack.top() is now " << mystack.top() << endl; return 0; }
输出:mystack.top() is now 15
bool empty ( ) const; 检测是否为空。