众所周知,对于vector<pair<int, int> >
若直接使用sort
排序,会默认按照pair
的第一个关键字从小到大进行排序:
#include <bits/stdc++.h>using namespace std;int main()
{vector<pair<int, int> > p;p.push_back({1, 3});p.push_back({4, 2});p.push_back({2, 5});sort(p.begin(), p.end());for (auto i : p) {cout << i.first << " " << i.second;puts("");}return 0;
}
其输出结果为:
若想要更改其排序规则,可以考虑使用自定义cmp
函数并添加在sort
的第三个参数位置,
但使用 L a m b d a \rm Lambda Lambda表达式则更为简单。如下代码对pair
按照第二个关键字从小到大排序。
#include <bits/stdc++.h>using namespace std;int main()
{vector<pair<int, int> > p;p.push_back({1, 3});p.push_back({4, 2});p.push_back({2, 5});sort(p.begin(), p.end(), [](const pair<int, int> &a, const pair<int, int> &b) {return a.second < b.second;});for (auto i : p) {cout << i.first << " " << i.second;puts("");}return 0;
}
其输出结果为:
与以下代码完全等价。
#include <bits/stdc++.h>using namespace std;bool cmp(const pair<int, int> &a, const pair<int, int> &b) {return a.second < b.second;
}
int main()
{vector<pair<int, int> > p;p.push_back({1, 3});p.push_back({4, 2});p.push_back({2, 5});sort(p.begin(), p.end(), cmp);for (auto i : p) {cout << i.first << " " << i.second;puts("");}return 0;
}
类似的,也可以按照第一个关键字与第二个关键字之和的大小来排序,对应的 L a m b d a \rm Lambda Lambda表达式应这样书写:
sort(p.begin(), p.end(), [](const pair<int, int> &a, const pair<int, int> &b) {return a.first + a.second < b.first + b.second;});
当然也可以写作
sort(p.begin(), p.end(), [&](const pair<int, int> a, const pair<int, int> b) {return a.first + a.second < b.first + b.second;});
其中[&]
表示按引用的方式捕获变量。
更多的,结构体的自定义排序也可以采用 L a m b d a \rm Lambda Lambda表达式。例如:
struct Range
{int l, r;
}t[N];sort(t, t + n, [](const Range &a, const Range &b) {return a.r < b.r;});
等价于
struct Range
{int l, r;bool operator< (const Range &W)const{return r < W.r;}
}t[N];sort(t, t + n);
均为按照Range
结构体的r
从小到大排序。