1. 现代C++20解决方案
auto cmp = [](int a, int b) { return ... };
std::set<int, decltype(cmp)> s;
We use 拉姆达函数 https://stackoverflow.com/q/7627098/5812238作为比较器。像往常一样,比较器应该返回布尔值,指示作为第一个参数传递的元素是否被认为位于特定的第二个参数之前严格弱序 https://en.wikipedia.org/wiki/Weak_ordering#Strict_weak_orderings它定义了。
在线演示 https://godbolt.org/z/AL2wo-
2. 现代C++11解决方案
auto cmp = [](int a, int b) { return ... };
std::set<int, decltype(cmp)> s(cmp);
在 C++20 之前,我们需要将 lambda 作为参数传递给 set 构造函数
在线演示 https://ideone.com/WAu8EU
3. 与第一个解决方案类似,但用函数代替 lambda
使比较器像平常的布尔函数一样
bool cmp(int a, int b) {
return ...;
}
然后使用它,可以这样:
std::set<int, decltype(cmp)*> s(cmp);
在线演示 https://ideone.com/LhYOvK
或者这样:
std::set<int, decltype(&cmp)> s(&cmp);
在线演示 https://ideone.com/tBwrUI
4.使用struct with的旧解决方案()
操作员
struct cmp {
bool operator() (int a, int b) const {
return ...
}
};
// ...
// later
std::set<int, cmp> s;
在线演示 https://ideone.com/M6azNB
5.替代解决方案:从布尔函数创建结构
取布尔函数
bool cmp(int a, int b) {
return ...;
}
并使用它来构造结构std::integral_constant https://en.cppreference.com/w/cpp/types/integral_constant
#include <type_traits>
using Cmp = std::integral_constant<decltype(&cmp), &cmp>;
最后,使用结构体作为比较器
std::set<X, Cmp> set;
在线演示 https://ideone.com/jxUPkX