【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
*/