stack_初探

博客内容主要介绍了STL中的stack,属于信息技术领域数据结构相关知识。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本节介绍一下STL中的stack

#include<iostream>
#include<cstdio>
#include<stack>
using namespace std;
int main()
{
	//本节学习STL-stack,同理定义方式和其他STL容器别无二致
	printf("create a stack and push 1~5\n");
	stack<int> st;
	//push()用于将元素压栈,O(1) 
	for(int i=1;i<=5;i++)
		st.push(i);
	//top()可以返回栈顶元素,也可以直接访问,O(1) 
	int m=st.top();
	printf("the top is %d m=st.top() m = %d\n",st.top(),m);
	//pop()可以把栈顶元素弹出,O(1),返回值为void
	for(int i=0;i<3;i++)
		st.pop();
	printf("After pop 3 times the top is %d\n",st.top());
	//size()用来返回stack内的元素个数,O(1)
	printf("Now the size of st is %d\n",st.size()); 
	//empty()用于检测stack是否为空,为空返回true,否则返回false,O(1)
	printf("create a empty stack st2\n");
	stack<int> st2;
	printf("so the st is ");
	if(st.empty()==true)
		printf("Empty\n");
	else
		printf("Not Empty\n");
	printf("so the st2 is ");
	if(st2.empty()==true)
		printf("Empty\n");
	else
		printf("Not Empty\n");
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值