C++ STL(Standard Template Library)标准库一一栈、队列和优先队列

栈、队列和优先队列

栈 ( 后进先出 )

STLstack 头文件提供了栈,用 stack< int > s 方式定义。

  1. push(x) 入栈 x 元素
  2. pop() 出栈
  3. empty() 堆栈为空则返回真
  4. size() 返回栈中元素数目
  5. top() 返回栈顶元素
#include<iostream>
#include<string>
#include<stack>
using namespace std;
int main(){
	stack<string> s;
	s.push("A");
	s.push("B");
	s.push("C");
	s.push("D");
	s.pop(); // D 出栈
	cout<<s.top()<<endl; //输出栈顶 C
	cout<<s.size()<<endl; //栈中元素的数目 3
	cout<<s.empty()<<endl; // 栈不为空,输出0
	return 0;
}

队列

STL队列定义在头文件 < queue > 中,用 " queue< int > s " 声明一个队列。

  1. push(x) 在队尾压入新元素
  2. pop() 删除队列首元素但不返回其值
  3. empty() 如果队列为空返回true,否则返回false
  4. size() 返回队列中元素的个数
  5. front() 返回队首元素的值,但不删除该元素
  6. back() 返回队尾元素的值,但不删除该元素
#include<iostream>
#include<queue>
#include<string>
using namespace std;
int main() 
{
	queue<string> s;
	s.push("A");
	s.push("B");
	s.push("C");
	s.push("D");
	s.pop(); //删除队首元素 A
	cout << s.front() << endl; //队首元素 B
	cout << s.back() << endl; //队尾元素 D
	cout << s.size() << endl; //队中元素的个数 3
	cout << s.empty() << endl; 
	return 0;
}

优先队列

STL的queue头文件提供了优先队列,用 “priority_queue < int > s” 方式定义。
这个s默认是less降序排序是一个“越小的整数优先级越低的优先队列”。由于出队元素并不是最先进队的元素,出队的方法由 front() 变为top()

  1. 升序队列 priority_queue <int,vector<int>,greater<int> > s
  2. 降序队列 priority_queue <int,vector<int>,less<int> > s
#include<iostream>
#include<functional>
#include<queue>
using namespace std;
int main()
{
	//priority_queue<int>pq; 与less一样 10401
	priority_queue<int, vector<int>, greater<int> > pq;
	pq.push(10001);
	pq.push(1000);
	pq.push(10401);
	pq.push(1002);
	cout << pq.top() << endl; //1000
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值