STL中的一般栈类实现为容器适配器:它使用一个容器,并让它按照指定的方式工作。栈容器不是重新创建的,它只是对已有容器做适当的调整,默认的情况下,双端队列(deque)是基础容器,但是用户可以用下面的声明选择链表或者向量
stack<int> stack1; //默认为双端队列
stack<int, vector<int> > stack2; //向量 两个>之间要有空格
stack<int, list<int> > stack3; //链表
构造函数:
#include <stack>
stack();
stack( const Container& con );
成员函数:
|
empty |
true if the stack has no elements |
|
pop |
removes the top element of a stack |
|
push |
adds an element to the top of the stack |
|
size |
returns the number of items in the stack |
|
top |
returns the top element of the stack |
中文:
|
成员函数 |
实现操作 |
| bool empty()const |
如果栈为空,则返回true,否则返回false |
| void pop() |
移去栈的栈顶元素 |
| void push(const T& el) |
将el插入到栈的顶端 |
| size_type size()const |
返回栈中元素数目 |
| stack() |
创建一个空栈 |
| T& top() |
返回栈顶元素 |
| const T& top() const |
返回栈顶元素 |
注意:pop() 函数返回的是void类型,也就是说pop()不返回从栈中弹出的元素,所以如果在出栈时要保存栈顶元素,应该先用top()函数返回栈顶元素再出栈。
本文详细介绍了C++标准模板库(STL)中的栈类实现及其使用方法。包括栈类的构造函数、成员函数如empty、pop、push、size及top等,并解释了如何通过不同的容器如双端队列、向量和链表来实现栈。
2812

被折叠的 条评论
为什么被折叠?



