有时候我们需要对数组或者其他数据结构按照某一指定的元素排序
比如在使用结构体时,结构体内有许多元素,这时候常规的 sort 方法无法识别按哪一个元素排序,或者只能自己花时间写详细的排序算法,这太麻烦了。于是,我们不妨做个调库小王子
如果要按照某一特定元素排序,可以使用如下方法:
调用优先队列
重载运算符
例子如下,通过重载大于小于运算符的方式,来指定有序数据结构 (如优先队列) 的排序方式
1 2 3 4 5 6 7 8 9 10 11 12 13
| #include<queue> using namespace std; struct node { int x; int y; friend bool operator<(node a, node b) { return a.x < b.x; } }; priority_queue<node> q;
|
自定义排序规则
例子如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| #include <iostream> #include <vector> #include <queue> using namespace std; struct node { int x; int y; }; struct sort_by_x { bool operator()(node a, node b){ return a.x < b.x; } }; priority_queue<node,vector<node>,sort_by_x> q;
|
调用 sort 函数
传入自定义排序函数
我们可以定义排序的函数,然后传入这个函数指针即可
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| #include<algorithm> using namespace std; struct node{ int x; int y; } bool cmp_x(node a,node b){ return a.x>b.x; } int main(){ int n=10; node *px=new node [n]; sort(px,px+n,cmp_x); }
|
lamda 表达式
也可以使用更简洁的 lambda
表达式 (c++ 11
版本及以上支持)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| #include <iostream> #include <vector> #include <algorithm> using namespace std;
struct test { int n = 0; int w = 0; };
int main() { vector<test> t; t.push_back({1, 2}); t.push_back({3, 4}); t.push_back({5, 6}); sort(t[0], t[2], [](test a, test b) { return a.w < b.w; }); for (auto i : t) cout << " " << i.w << endl; }
|
PS: python 中的列表也有类似的语法,如下
1 2 3
| num = [(2, 2), (3, 4), (4, 1), (1, 3)]
num.sort(key=lambda ele: ele[1], reverse=True)
|