C++ STL stack 用法

tech2025-09-30  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,100); //构造一个包含3个int元素的双端队列 stack<int> second (mydeque); //用自己的双端队列构造一个栈(size=3) stack<int,vector<int> > third; //指明用vector实现一个栈(存放int),空栈size=0 vector<int> myvector (2,200); //构造一个存放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 0; }

输出结果:

size of first: 0 size of second: 3 size of third: 0 size of fourth: 2

成员函数

先说一些常用的,直接看例子

#include <iostream> #include <stack> using namespace std; int main () { stack<int> mystack; for (int i=0; i<5; ++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 0; }

运行结果:

size: 5 4 3 2 1 0

再来看另一组例子:

#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(1,2); //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 0; }

运行结果:

1 2 0 1

 

承接Matlab、Python和C++的编程,机器学习、计算机视觉的理论实现及辅导,本科和硕士的均可,详谈请联系QQ号757160542

 

最新回复(0)