STL 中的栈容器
栈容器用于在 c++ 中复制栈,插入和删除总是在栈的顶部执行。
要了解更多关于栈数据结构的信息,请访问:栈数据结构
以下是在 stl 中定义栈的语法:
**stack**<object_type> *stack_name*;
上面的语句将创建一个名为对象类型的栈名。
栈容器的成员函数
以下是 STL 中栈容器最常用的一些函数:
push
功能
push()用于将元素插入到栈中,元素被插入到栈的顶部。
#include <iostream>
#include <stack>
using namespace std;
int main ()
{
**stack**<int> s; *// creates an empty stack of integer s*
s.**push**(2); *// pushes 2 in the stack , now top =2*
s.**push**(3); *// pushes 3 in the stack , now top =3*
}
pop
功能
此方法用于从栈中移除单个元素。它将栈的大小减少了 1。移除的元素始终是栈的最顶层元素(最近添加的元素)。pop()
方法不返回任何东西。
top
功能
此方法返回栈的最顶层元素。请注意,与 pop()不同,此方法返回元素,而不是移除它。
语法:top()
size
和empty
功能
size()
返回栈中存在的元质数量,而empty()
检查栈是否为空。如果栈为空,则 empty 返回 true,否则返回 false。
swap
功能
此方法交换两个栈的元素。
#include <iostream>
#include <stack>
using namespace std;
int main ()
{
**stack**<int> s;
*// pushing elements into stack*
s.**push**(2);
s.**push**(3);
s.**push**(4);
cout << s.**top**(); *// prints 4, as 4 is the topmost element*
cout << s.**size**(); *// prints 3, as there are 3 elements in*
}