C++ STL stack 用法

2023-06-12,,

Stack(栈)是一种后进先出的数据结构,也就是LIFO(last in first out) ,最后加入栈的元素将最先被取出来,在栈的同一端进行数据的插入与取出,这一段叫做“栈顶”。

使用STL的stack需要include一个头文件<stack>

构造

template <class T, class Container = deque<T> > class stack;

如上,这对尖括号中有两个参数,第一个是T,表示栈中存放的数据的类型,比如int,double,或者结构体之类。

第二个参数指明底层实现的容器类型,也就是指明这个栈的内部实现方式,比如vector,deque,list。如果不指明它,默认使用deque(双端队列)。当然一般情况下不需要指定这一项参数。

直接看栗子、

// 构造 stacks
#include <iostream>
#include <stack> // 使用栈stack
#include <vector> // vector
#include <deque> // deque
using namespace std; int main ()
{
stack<int> first; //构造一个用于存放int类型的空栈(默认底层容器为deque),size=0。这是最简单也是最常用的方式 ٩(๑❛ᴗ❛๑)۶如果感觉别的方式太复杂,会用这一种就行 deque<int> mydeque (,); //构造一个包含3个int元素的双端队列
stack<int> second (mydeque); //用自己的双端队列构造一个栈(size=3) stack<int,vector<int> > third; //指明用vector实现一个栈(存放int),空栈size=0 vector<int> myvector (,); //构造一个存放2个元素的vector
stack<int,vector<int> > fourth (myvector); //用自己的vector构造一个栈,size=2 //输出四个栈的大小
cout << "size of first: " << first.size() << endl;
cout << "size of second: " << second.size() << endl;
cout << "size of third: " << third.size() << endl;
cout << "size of fourth: " << fourth.size() << endl; return ;
}

输出结果:

size of first:
size of second:
size of third:
size of fourth:

成员函数

先说一些常用的,直接看栗子୧(๑•̀⌄•́๑)૭

#include <iostream>
#include <stack>
using namespace std; int main ()
{
stack<int> mystack; for (int i=; i<; ++i) mystack.push(i); //push函数将参数元素加入栈中,没有返回值(例如这里循环将0,1,2,3,4加入栈中,注意栈顶元素是4)
cout << "size: " << mystack.size() << endl; //size函数返回栈的大小(此时有5个元素,size=5) while (!mystack.empty()) //empty函数返回一个bool值,栈为空时返回true,否则返回false
{
cout << ' ' << mystack.top(); //top函数的返回值是栈顶元素(注意并没有删掉栈顶元素)
mystack.pop(); //pop函数将栈顶元素删掉,没有返回值
}
cout << endl; return ;
}

运行结果:

size:
     

再来看另一组栗子:

#include <iostream>
#include <stack>
using namespace std; struct Node {
int a,b;
Node (int x, int y) {
a = x; b = y;
}
}; int main ()
{
stack<Node> mystack;
mystack.emplace(,); //emplace函数可以将一个元素加入栈中,与push的区别在于:emplace可以直接传入Node的构造函数的参数,并将构造的元素加入栈中
//mystack.push(1,2); //编译不通过,要达到上面的效果需要手动构造,例如mystack.push(Node(1,2));
Node p = mystack.top();
cout << p.a << " " << p.b << endl; stack<Node> my2;
my2.swap(mystack); //swap函数可以交换两个栈的元素
cout << mystack.size() << " " << my2.size() << endl; return ;
}

运行结果:

 

以上就是stack的常规操作

C++ STL stack 用法的相关教程结束。

《C++ STL stack 用法.doc》

下载本文的Word格式文档,以方便收藏与打印。