6.7 stack的常见用法详解

​ 栈是STL中实现的一个后进先出的容器

1. stack的定义

​ 要使用stack,应先添加头文件#include

stack<typename> name;

2. stack容器内元素的访问

​ 由于栈(stack)本身就是一种后进先出的数据结构。在STL中stack中只能通过top()来访问栈顶元素

#include <bits/stdc++.h>
#include <stack>
using namespace std;
int main(){
	stack<int> st;
	for(int i = 0; i < 5; i++){
		st.push(i);
	}
	cout<<st.top()<<endl;
	return 0;
} 
输出结果:
    4

3. stack常用函数实例解析

(1). push(x) 将x入栈
(2). top() 获得栈顶元素
(3). pop() 用以弹出栈顶元素
(4). empty() 可以检测stack内是否为空,返回true为空,返回false为非空
(5). size() 返回stack内元素的个数

4. stack的常见用途

​ stack用来模拟实训一些递归,防止程序对栈内存的限制而导致程序运行出错

​ 用栈来模拟递归算法的实训,则可以避免内存溢出等等这一方面的问题

实践

// 2、 栈
#include <bits/stdc++.h>
#include <stack>
#include <map>
#include <set>
#include <vector>
using namespace std;
int main(){
	stack<int> s;		//栈的定义 
	s.push(1);
	s.push(2);
	s.push(3);			//入栈 
	cout<<s.top()<<endl;		//获取栈顶元素
	s.pop();					//弹出栈顶元素 
	cout<<s.top()<<endl; 
	cout<<s.empty()<<endl;		//判断栈是否为空 
	cout<<s.size()<<endl;		//输出栈的元素个数 
	return 0;
} 
/*
3
2
0
2
*/
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐