资源
| Resources | |||||
|---|---|---|---|---|---|
| fushar | 涵盖本模块的全部内容。 | ||||
| CPP | 参考资料 | ||||
简介
如果想把使用自定义比较器排序中定义的 Edge 结构体用于 C++ 的 set,该怎么办?
Warning!
本模块的代码假设所有 w 值互不相同。
要正确处理 w 相等的情况,请用 std::multiset 代替 std::set。
运算符重载
这种方法的行为与预期一致,但必须确保写上第二个 const,否则会产生编译错误。上方链接解释道:
[第二个 const] 表示你不能修改当前对象的成员变量。
#include <bits/stdc++.h>using namespace std;struct Edge {int a, b, w;bool operator<(const Edge &y) const { return w < y.w; }};int main() {int M = 4;
比较器
| Resources | |||||
|---|---|---|---|---|---|
| SO | |||||
使用函数
#include <bits/stdc++.h>using namespace std;struct Edge {int a, b, w;};bool cmp(const Edge &x, const Edge &y) { return x.w < y.w; }int main() {
也可以用下面的语法声明使用函数作为比较器的集合 v:
set<Edge,decltype(&cmp)> v(cmp);
使用 Lambda 表达式
auto cmp = [](const Edge &x, const Edge &y) { return x.w < y.w; };int main() {int M = 4;set<Edge, bool (*)(const Edge &, const Edge &)> v(cmp);for (int i = 0; i < M; ++i) {int a, b, w;cin >> a >> b >> w;v.insert({a, b, w});}for (Edge e : v) cout << e.a << " " << e.b << " " << e.w << "\n";}
也可以用下面的语法声明使用 Lambda 表达式作为比较器的集合 v:
set<Edge,decltype(cmp)> v(cmp);
尽管 decltype(cmp) 实际上并不等价于 bool(*)(const Edge&,const Edge&)。
详情请参阅 Lambda 表达式。
函数对象
这种方法可能比上面的方法更易理解。
#include <bits/stdc++.h>using namespace std;struct Edge {int a, b, w;};struct cmp {bool operator()(const Edge &x, const Edge &y) const { return x.w < y.w; }};
实用技巧
一个函数对象可以供多个对象使用。
还可以在 cmp 后加上 (),像普通函数一样使用它。
int main() {int M = 4;vector<Edge> v;for (int i = 0; i < M; ++i) {int a, b, w;cin >> a >> b >> w;v.push_back({a, b, w});}sort(begin(v), end(v), cmp());for (Edge e : v) cout << e.a << " " << e.b << " " << e.w << "\n";}
内置函数对象
重载小于运算符(<)会自动生成函数对象
less<Edge>。
类似地,重载(>)会自动生成函数对象
greater<Edge>。
可以利用它按逆序存储集合。
#include <bits/stdc++.h>using namespace std;struct Edge {int a, b, w;bool operator>(const Edge &y) const { return w > y.w; }};int main() {int M = 4;
其他容器
以下写法都是合法的:
set<int, greater<int>> a;map<int, string, greater<int>> b;priority_queue<int, vector<int>, greater<int>> c;
为优先队列使用自定义比较器尤其常见。C++ 优先队列默认弹出最大元素, 而上面的代码会使其改为弹出最小元素。
题目
可以查看扫描线模块,其中有一道使用自定义比较器集合的题目。