C++中stack头文件的使用

头文件:

#include<stack>

定义:

stack<int> s1;
stack<string> s2;

基本操作:

s.push(x);  //入栈
s.pop();  //出栈,只是删除栈顶元素,并不返回该元素
s.top()//访问栈顶元素
s.empty()//判断栈空,当栈空时,返回true
s.size()//访问栈中元素个数

整体代码:

#include <stack>   //后进先出 
#include <cstdio> 
using namespace std;
int main()
{
	stack<int> s;  //声明一个int类型的栈 
	for(int i = 1; i < 10; i++)
		s.push(i);  //将 1~9放入栈中 
	printf("%d\n",s.size());  //输出栈中数据元素的个数 
	printf("%d\n",s.top());    //访问最顶端的数据 
	s.pop();     //移除最顶端的数据 
	printf("%d\n",s.top());
	s.pop();
	printf("%d\n",s.top());
	s.pop();
	printf("%d\n",s.size());  //输出栈中数据元素的个数 
	if(s.empty())   //判断栈是否为空 
		printf("栈空\n");  //为空 
	else
		printf("栈非空\n");  //非空 
	return 0;
}

运行结果:
在这里插入图片描述

发布了12 篇原创文章 · 获赞 45 · 访问量 3872

猜你喜欢

转载自blog.csdn.net/weixin_45897672/article/details/103963270