STL专题-栈(stack)

栈(stack)
在这里插入图片描述
stack是一种先进后出(First In Last Out, FILO)的数据结构(如同一个死胡同,最先进去的人必定是最后出来的)
头文件:#include
定义:stack<data_type> stack_name;
stack s;
运算函数:
empty() – 返回bool型,表示栈内是否为空 (s.empty() )
size() – 返回栈内元素个数 (s.size() )
top() – 返回栈顶元素值 (s.top() )
pop() – 移除栈顶元素(s.pop(); )
push(data_type a) – 向栈压入一个元素 a(s.push(a); )
代码如下:

#include <iostream>
#include <stack>
#include <algorithm>
using namespace std;
int main() {

	stack<int>s;
	s.push(1);
	s.push(2);
	s.push(3);
	cout << "Top: " << s.top() << endl;
	cout << "Size: " << s.size() << endl;
	s.pop();
	cout << "Size: " << s.size() << endl;
	if (s.empty()) {
		cout << "Is empty" << endl;
	}
	else { cout << "Is not empty" << endl; }    	return 0;
}

上述代码所得结果为

Top: 3
Size: 3
Size: 2
Is not empty
发布了90 篇原创文章 · 获赞 15 · 访问量 3168

猜你喜欢

转载自blog.csdn.net/qq_43656233/article/details/87930289