我正在尝试使用带有捕获值的 lambda 来声明一个带有比较函数的 std::set 以指定元素的顺序。
我已经尝试使用捕获的值创建一个 lambda,然后将该 lambda 作为模板化参数传递给 std::set。 我也尝试过使用仿函数,但也无法使其正常工作。
//Using a lambda
int value = 3; //This is not known at compile time
std::function cmp = [&value](int a, int b){
return value > 123 ? a < b : a >= b;
};
std::set<int, cmp> mySet;
// Using a functor
class Cmp{
int value;
public:
Cmp(int value) : value(value){};
bool operator()(const int&a, const int& b){
return value > 123 ? a < b : a >= b;
}
};
int val = 3; //This is not known at compile time
Cmp cmp(val);
set<int, cmp> mySet;
我在使用 lambda 时遇到此错误:
note: a lambda closure type has a deleted default constructor
使用仿函数时的这个:
error: no matching function for call to ‘Cmp::Cmp()’
最佳答案
您不能在模板参数中传递运行时变量。
Compare
std:set
的模板参数需要一个类型名,而不是一个变量。匹配类型名的实际比较函数可以传递给 set::set
构造函数。
试试这个:
//Using a lambda
int value = 3; //This is not known at compile time
auto cmp = [&value](int a, int b){
return value > 123 ? a < b : a >= b;
};
std::set<int, decltype(cmp)> mySet(cmp);
//Using a functor
class MySetComparer{
int value;
public:
MySetComparer(int value) : value(value) {}
bool operator()(int a, int b) const {
return value > 123 ? a < b : a >= b;
}
};
int val = 3; //This is not known at compile time
MySetComparer cmp(val);
set<int, MySetComparer/*decltype(cmp)*/> mySet(cmp);
注意:无论哪种方式,请注意您的比较器使用 a >= b
休息 strict weak ordering的 Compare标准 C++ 容器使用的要求:
The return value of the function call operation applied to an object of a type satisfying Compare, when contextually converted to
bool
, yieldstrue
if the first argument of the call appears before the second in the strict weak ordering relation induced by this type, andfalse
otherwise.
a < b
满足该要求,但是 a >= b
不会,当 value > 123
时,这将导致您的代码在运行时发生未定义的行为不是真的。
关于c++ - 使用具有捕获值的 lambda 对容器进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58511398/