重点总结:
std::stack
是一个先进后出(FILO)的容器,为了严格遵循FILO,stack
不提供元素的任何迭代器操作。std::stack
是一种容器适配器,提供特定的函数来访问元素。stack
只能从容器的一端(栈顶)进行插入、删除、访问操作。std::stack
的基本操作示意图如下所示。本文参考自std::stack。
1. Stack与构造函数
stack
的底层容器可以是任意容器类模板或者一些其他特定的容器类,这些容器类需支持以下操作:empty()
、 back()
、push_back()
、pop_back()
、emplace()
。
STL中std::vector
、std::deque
、std::list
均符合上述要求,std::stack
底层默认使用deque
。
- Stack的构造函数有如下几种类型(www.cplusplus.com)。
- [1]. 通过容器对象进行构造
- [2]. 同1,参数为右值
- [3]. std::allocator对象作为参数
- [4]. 通过容器对象、std::allocator进行构造
- [5]. 复制构造 with std::allocator
- [6]. 移动构造 with std::allocator
例:
int main ()
{
std::deque<int> mydeque(3,100); // deque with 3 elements
std::vector<int> myvector(2,200); // vector with 2 elements
std::stack<int> first; // empty stack
std::stack<int> second(mydeque); // [1]. 复制构造,通过deque
std::stack<int,std::vector<int> > third; // empty stack using vector
std::stack<int,std::vector<int> > fourth(myvector);
std::cout << "size of first: " << first.size() << '\n';
std::cout << "size of second: " << second.size() << '\n';
std::cout << "size of third: " << third.size() << '\n';
std::cout << "size of fourth: " << fourth.size() << '\n';
return 0;
}
size of first: 0
size of second: 3
size of third: 0
size of fourth: 2
2. empty()、size()
- 函数
empty()
判断stack容器是否为空。 - 函数
size()
返回stack容器中元素个数。函数原型如下:
bool empty() const;
size_type size() const;
例:
int main ()
{
std::stack<int> first;
std::cout << "is empty:" << first.empty() << ", size:" << first.size() << endl;
first.push(1);
std::cout << "is empty:" << first.empty() << ", size:" << first.size() << endl;
return 0;
}
is empty:1, size:0
is empty:0, size:1扫描二维码关注公众号,回复: 12641196 查看本文章
3. push()、pop()、top()
- 函数
push()
在栈顶插入元素,这个元素是新的栈顶元素。 - 函数
pop()
删除栈顶元素,其size大小减1。 - 函数
top()
返回栈顶元素的引用,函数原型如下:
void push (const value_type& val);
void push (value_type&& val);
void pop();
reference& top();
const_reference& top() const;
例:
int main ()
{
std::stack<int> mystack;
for (int i=0; i<5; ++i)
mystack.push(i); // 入栈: 0 1 2 3 4
std::cout << "Popping out elements...";
while (!mystack.empty())
{
std::cout << ' ' << mystack.top(); // 打印栈顶元素
mystack.pop(); // 出栈
}
std::cout << '\n';
return 0;
}
Popping out elements… 4 3 2 1 0
4. swap()、emplace()
- 函数
swap()
将本容器中的元素与参数容器中的元素互换。 - 函数
emplace()
栈顶插入元素(移动构造对象),关于移动语义见右值、移动语义。 - 函数原型如下:
void swap(stack& x) noexcept(/*see below*/);
template <class... Args> void emplace(Args&&... args);
例:
int main ()
{
std::stack<int> foo,bar;
foo.push(10);
foo.push(20);
foo.push(30);
bar.emplace(111);
bar.emplace(222); // emplace
foo.swap(bar);
std::cout << "foo-";
print_stack_int(foo); // foo-Stack size:2and element: 222 111
std::cout << "bar-";
print_stack_int(bar); // bar-Stack size:3and element: 30 20 10
return 0;
}