stack

阅读量: 254 编辑

stack 是 C++ 标准模板库提供的一个栈容器实现。

栈是一种后进先出(Last-In-First-Out, LIFO)的数据结构,即最后进入的元素是第一个被取出的。

函数用法

  • stack<int> s; 创建一个空栈

  • s.push(e):向栈顶添加元素 e

  • s.pop():从栈顶移除元素(不返回元素的值)

  • s.top():获取栈顶元素(不移除)

  • s.empty():判断栈是否为空

  • s.size():返回栈中的元素个数

参考程序

// 爱码岛编程
#include <bits/stdc++.h>
using namespace std;

int main(){
	
	stack<int> s;
	
	cout << s.size() << endl; // 元素个数 
	cout << s.empty() << endl; // 是否为空,true 
	
	// 入栈 
	s.push(10);
	s.push(20);
	s.push(30);
	s.push(40);
	
	cout << s.top() << endl; //获取栈顶的元素 
	cout << s.size() << endl; 
	
	// 出栈 
	s.pop();
	cout << s.top() << endl; //获取栈顶的元素 
	cout << s.size() << endl;
	
	cout << endl;
	while(!s.empty()){
		cout << s.top() << endl;
		s.pop();
	}
	
	return 0;
}
爱码岛编程公众号
试卷资料
爱码岛编程小程序
在线刷题
苏ICP备13052010号
©2023 南京匠成信息科技有限公司