C++-STL-栈、队列、优先队列

本文详细介绍了栈和队列这两种常用的数据结构,包括它们的特点、基本操作及使用示例。栈遵循后进先出原则,而队列则是先进先出。此外,还探讨了优先队列及其实现方式。

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

栈:后进先出(last in first out LIFO)
头文件 stack < stack >

stack < int > s;

栈的基本操作:

  1. s.empty() 如果栈为空返回true,否则返回false
  2. s.size() 返回栈中元素的个数
  3. s.pop() 删除栈顶元素但不返回其值
  4. s.top() 返回栈顶的元素,但不删除该元素
  5. s.push() 在栈顶压入新元素
#include<iostream>
#include<stack>
using namespace std;
int main()
{
	 stack<int>s;
	 int n;
	 cin>>n;
	 for(int i=0;i<n;i++)
	 {
		  int a;
		  cin>>a;
		  s.push(a);
	 }
	 while(!s.empty())   //s.empty()  空返回true 否则false 
	 {
		  cout<<s.top();
		  s.pop();
		  cout<<endl;
	 }
	 return 0;
 } 

队列:先进先出 (Frist In Frist Out,FIFO)

头文件 #include< queue >
queue< int >q;
队列的基本操作:

  1. q.empty() 如果队列为空返回true,否则返回false
  2. q.size() 返回队列中元素的个数
  3. q.pop() 删除队列首元素但不返回其值
  4. q.front() 返回队首元素的值,但不删除该元素q
  5. .push() 在队尾压入新元素
  6. q.back() 返回队列尾元素的值,但不删除该元素
#include<iostream>
#include<queue>
using namespace std;
int main()
{
	 queue<string>s;
	 int n;
	 cin>>n;
	 for(int i=0;i<n;i++)
	 {
		  string a;
		  cin>>a;
		  s.push(a);
	 }
	 while(!s.empty())
	 {
		  cout<<s.front()<<endl;
		  s.pop(); 
	 }
	 return 0;
} 

优先队列:默认为越小的整数优先级越低(从大到小排序)

头文件:#include< queue >

定义:priority_queue< int >s1; (默认越小的整数优先级越低)

cmp设置越大的整数优先级越低(从小到大排序)
两种方法:
1.直接声明:

priority_queue<int ,vector<int>,greater<int> > s2;

2.运用结构体重载

struct cmp{
	 bool operator() (const int a,const int b) const{
		 return a>b;
 }
};

priority_queue<int,vector<int>,cmp>s;

基本操作:

  1. q.size();//返回q里元素个数
  2. q.empty();//返回q是否为空,空则返回1,否则返回0
  3. q.push(k);//在q的末尾插入k
  4. q.pop();//删掉q的第一个元素
  5. q.top();//返回q的第一个元素

代价:

#include<iostream>
#include<queue>
using namespace std;
struct cmp{
	 bool operator() (const int a,const int b) const{
	 	return a>b;
	 }
};
int main()
{
	 priority_queue<int>s1;
	 priority_queue<int ,vector<int>,greater<int> > s2;
	 priority_queue<int,vector<int>,cmp>s;
	 int n;
	 cin>>n;
	 for(int i=0;i<n;i++)
	 {
		  int a;
		  cin>>a;
		  s.push(a);
	 }
	 while(!s.empty())
	 {
		  cout<<s.top()<<endl;
		  s.pop(); 
	 }
	 return 0;
} ```
	
	  	
	
	
	
	

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

aaHua_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值