利用 STL priority_queue 进行数据排序

本文详细介绍了STL中的priority_queue,包括其功能、模板声明、常用函数以及如何实现升序和降序排序。通过实例展示了如何使用priority_queue处理整数和字符串,并提供了相应的代码实现。了解这些内容能帮助开发者更有效地利用STL进行排序和优先级操作。
摘要由CSDN通过智能技术生成

【STL priority_queue 官方链接】
STL priority_queue 的功能强大在哪里呢? 四个字:自动排序
其官方文档链接为:
http://www.cplusplus.com/reference/queue/priority_queue/

【STL priority_queue模板声明】
STL priority_queue模板声明带有三个参数:priority_queue<Type, Container, Functional>
其中:Type为数据类型;Container为保存数据的容器。默认为vector。此外,还可用其他用数组实现的容器,比如 deque;Functional为元素比较方式。默认为 operator<

  • 利用 priority_queue<int> pq; 声明元素递减的优先队列。
  • 利用 priority_queue<int,vector<int>,greater<int> > pq; 声明元素递增的优先队列。 (注意:后面两个“>”之间要有一个空格,不要写在一起。因为,“>>”是右移运算符。)


【STL priority_queue 常用函数】

empty() - Returns whether the priority_queue is empty
size() - Returns the number of elements in the priority_queue
top() - Returns a constant reference to the top element in the priority_queue
push () - Inserts a new element in the priority_queue
pop() - Removes the element on top of the priority_queue

【算法代码:降序
核心在于利用 priority_queue<int> pq; 声明了一个元素递减的优先队列。
之后,每入队一个元素,
自动递减排序。

#include<bits/stdc++.h>
using namespace std;

int n,x;

int main () {
	priority_queue<int> pq;
	cin>>n;
	for(int i=1;i<=n;i++){
		cin>>x;
		pq.push(x);
	}

	while(!pq.empty()){
		cout<<pq.top()<<" ";
		pq.pop();
	}

	return 0;
}


/*
in:
5
30 100 25 36 61
out:
100 61 36 30 25
*/

【算法代码:升序
核心在于利用 priority_queue<int,vector<int>,greater<int> > pq; 声明了一个元素递增的优先队列。
之后,每入队一个元素,
自动递增排序。

#include<bits/stdc++.h>
using namespace std;

int n,x;

int main () {
	priority_queue<int,vector<int>,greater<int> > pq;
	cin>>n;
	for(int i=1;i<=n;i++){
		cin>>x;
		pq.push(x);
	}

	while(!pq.empty()){
		cout<<pq.top()<<" ";
		pq.pop();
	}

	return 0;
}


/*
in:
5
30 100 25 36 61
out:
25 30 36 61 100
*/

【算法代码:字符串降序
核心在于利用 priority_queue<string> pq; 声明了一个字符串元素递减的优先队列。
之后,每入队一个字符串元素,
自动递减排序。

#include<bits/stdc++.h>
using namespace std;

int n;
string x;

int main () {
	priority_queue<string> pq;
	cin>>n;
	for(int i=1;i<=n;i++){
		cin>>x;
		pq.push(x);
	}

	while(!pq.empty()){
		cout<<pq.top()<<" ";
		pq.pop();
	}

	return 0;
}


/*
in:
5
opencv gis matlab python halcon
out:
python opencv matlab halcon gis
*/

【算法代码:字符串升序
核心在于利用 priority_queue<string,vector<string>,greater<string> > pq; 声明了一个字符串元素递增的优先队列。
之后,每入队一个字符串元素,
自动递增排序。

#include<bits/stdc++.h>
using namespace std;

int n;
string x;

int main () {
	priority_queue<string,vector<string>,greater<string> > pq;
	cin>>n;
	for(int i=1;i<=n;i++){
		cin>>x;
		pq.push(x);
	}

	while(!pq.empty()){
		cout<<pq.top()<<" ";
		pq.pop();
	}

	return 0;
}


/*
in:
5
opencv gis matlab python halcon
out:
gis halcon matlab opencv python
*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值