简介:
C++中的sort函数默认是将元素升序排列的,
而priority_queue默认是将元素降序排列的(默认实现的是大顶堆)。
一、自定义运算符
以下2种对sort和priority_queue运算符的重载都有效,效果都是一样的。
代码:
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
//sort实现的都是先按a值降序排列,a相同时,按b值降序排列
//priority_queue和sort的默认排序相反,实现的都是先按a值升序排列,a相同时,按b值升序排列
//重载方式一:
struct Node {
int a, b;
Node(int x, int y) {
a = x;
b = y;
}
bool operator < (const Node &c) const {
if(a == c.a) return b > c.b;
return a > c.a;
}
};
//重载方式二:注意要有public
// class Node {
// public:
// int a, b;
// Node(int x, int y) {
// a = x;
// b = y;
// }
// bool operator < (const Node &c) const {
// if(a == c.a) return b > c.b;
// return a > c.a;
// }
// };
int main()
{
vector<Node> v;
v.push_back(Node(1,2));
v.push_back(Node(1,4));
v.push_back(Node(4,2));
v.push_back(Node(3,3));
sort(v.begin(), v.end());
for(int i = 0; i < v.size(); ++i) {
cout<<v[i].a<<" "<<v[i].b<<endl;
}
cout<<endl;
priority_queue<Node> pq;
pq.push(Node(1,2));
pq.push(Node(1,4));
pq.push(Node(4,2));
pq.push(Node(3,3));
while(!pq.empty()) {
cout<<pq.top().a<<" "<<pq.top().b<<endl;
pq.pop();
}
return 0;
}
输出:
4 2
3 3
1 4
1 2
1 2
1 4
3 3
4 2
二、sort自定义运算符
代码:
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
//sort实现的都是先按a值降序排列,a相同时,按b值降序排列
//priority_queue和sort的默认排序相反,实现的都是先按a值升序排列,a相同时,按b值升序排列
struct Node {
int a, b;
Node(int x, int y) {
a = x;
b = y;
}
};
/*
//重载方式一:
struct compare {
bool operator()(const Node a, const Node b) {
if(a.a == b.a) return a.b > b.b;
return a.a > b.a;
}
} cmp;
*/
/*
//重载方式二:
bool cmp(const Node a, const Node b) {
if(a.a == b.a) return a.b > b.b;
return a.a > b.a;
}
*/
int main() {
vector<Node> v;
v.push_back(Node(1,2));
v.push_back(Node(1,4));
v.push_back(Node(4,2));
v.push_back(Node(3,3));
//重载方式一和二:
sort(v.begin(), v.end(), cmp);
//重载方式三:
sort(v.begin(), v.end(), [](const Node a, const Node b) {
if(a.a == b.a) return a.b > b.b;
return a.a > b.a;
});
for(int i = 0; i < v.size(); ++i) {
cout<<v[i].a<<" "<<v[i].b<<endl;
}
cout<<endl;
return 0;
}
输出:
4 2
3 3
1 4
1 2
三、priority_queue自定义运算符
代码:
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
//sort实现的都是先按a值降序排列,a相同时,按b值降序排列
//priority_queue和sort的默认排序相反,实现的都是先按a值升序排列,a相同时,按b值升序排列
struct Node {
int a, b;
Node(int x, int y) {
a = x;
b = y;
}
};
struct cmp {
bool operator()(const Node a, const Node b) {
if(a.a == b.a) return a.b > b.b;
return a.a > b.a;
}
};
int main() {
priority_queue<Node, vector<Node>, cmp> pq;
pq.push(Node(1,2));
pq.push(Node(1,4));
pq.push(Node(4,2));
pq.push(Node(3,3));
while(!pq.empty()) {
cout<<pq.top().a<<" "<<pq.top().b<<endl;
pq.pop();
}
return 0;
}
输出:
1 2
1 4
3 3
4 2
四、总结
比较:
类型 | sort | priority_queue |
---|---|---|
默认排序 | 升序 | 降序 |
设为升序 | less | greater |
设为降序 | greater | less |
重载 > 为 < | 降序 | 升序 |
重载 < 为 > | 降序 | 升序 |
重载 () 为 > | 降序 | 升序 |
重载 () 为 < | 升序 | 降序 |
在我看来,根本原因在于内部对优先级的定义不同!
来源:https://blog.csdn.net/qq_30534935/article/details/101073838