c++ - 使用具有捕获值的 lambda 对容器进行排序

标签 c++

我正在尝试使用带有捕获值的 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 orderingCompare标准 C++ 容器使用的要求:

The return value of the function call operation applied to an object of a type satisfying Compare, when contextually converted to bool, yields true if the first argument of the call appears before the second in the strict weak ordering relation induced by this type, and false otherwise.

a < b满足该要求,但是 a >= b不会,当 value > 123 时,这将导致您的代码在运行时发生未定义的行为不是真的。

关于c++ - 使用具有捕获值的 lambda 对容器进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58511398/

相关文章:

c++ - 尝试将对象存储在数组中,但如何调用该对象的方法?

c++ - 当我打开文件名在 std::string 中的 fstream 时,为什么会出现 "no matching function"错误?

c++ - 为什么我无法在 for 循环中访问动态分配的内存?

c++ - 模板元编程 : (trait for? ) 将指定模板分解为类型 T<T2,T3 N,T4, ...>

c++ - 谷歌 API 翻译

c++ - 使用特殊(德语)字符对 char * 进行排序?

c++ - 我们是否需要显式调用分配给 "simple POD classes"的 "placement new"的析构函数?

javascript - 调试 Chrome 原生消息传递

c++ - 使用可重定位设备代码时的 CUDA 8.0 Visual Studio 2012 链接器选项

C++ GUI事件/消息传递设计