有时候我们需要对数组或者其他数据结构按照某一指定的元素排序

比如在使用结构体时, 结构体内有许多元素, 这时候常规的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; //按x降序,要升序的话,改其中一个大于小于号就行
}
};

priority_queue<node> q;//此时创建的优先队列是按x大小降序排列的

自定义排序规则

例子如下

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
{ //按x降序
bool operator()(node a, node b){
return a.x < b.x;
}
};

priority_queue<node,vector<node>,sort_by_x> q;
//此时q是按x排序的. 注意要使用vector

调用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){//x降序
return a.x>b.x;
}

int main(){
int n=10;//此处也可以输入n,自定义大小
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)