目录
stack的定义
stack容器内元素的访问
stack常用函数实例解析
stack的常见用途
stack的定义
其定义的写法和其他STL容器相同,typename可以任意基本类型或容器:
stack<typename> name; 
stack容器内元素的访问
由于栈本身就是一种后进先出的数据结构,在STL的stack中只能通过top()来访问栈顶元素。
#include<iostream>
#include<stack>
using namespace std;
int main(){
	stack<int> st;
	for(int i=1;i<=5;i++){
		st.push(i);
	}
	printf("%d\n",st.top());
	return 0;
} 
stack常用函数实例解析
(1)push()
push(x)将x入栈,时间复杂度为
(2)top()
top()获得栈顶元素,时间复杂度为
(3)pop()
pop()用以弹出栈顶元素,时间复杂度为
#include<stdio.h>
#include<stack>
using namespace std;
int main(){
	stack<int> st;
	for(int i=1;i<=5;i++){
		st.push(i);
	}
	for(int i=1;i<=3;i++){
		st.pop();
	}
	printf("%d\n",st.top());
	return 0;
} 
(4)empty()
empty()可以检测stack内是否为空,返回true为空,返回false为非空,时间复杂度为
#include<iostream>
#include<stack>
using namespace std;
int main(){
	stack<int> st;
	if(st.empty()==true){
		printf("Empty\n");
	}
	else{
		printf("Not Empty\n");
	}
	st.push(1);
	if(st.empty()==true){
		printf("Empty\n");
	}
	else{
		printf("Not Empty\n");
	}
	return 0;
} 
(5)size()
size()返回stack内元素的个数,时间复杂度为
#include<stdio.h>
#include<stack>
using namespace std;
int main(){
	stack<int> st;
	for(int i=1;i<=5;i++){
		st.push(i);
	}
	printf("%d\n",st.size());
	return 0;
} 
stack的常见用途
stack用来模拟实现一些递归,防止程序对栈内存的限制而导致程序运行出错。


![[测试开发]如何让IDEA实时显示内存](https://img-blog.csdnimg.cn/direct/1e4e669e16dc4707bb75d95985b56acf.jpeg)

![[双指针] --- 快乐数  盛最多水的容器](https://img-blog.csdnimg.cn/direct/c5e6e191c4924779aaca0cf315c83c54.gif)














