如何用 lambda 排序?

2022-01-12 00:00:00 lambda sorting char constants c++
sort(mMyClassVector.begin(), mMyClassVector.end(), 
    [](const MyClass & a, const MyClass & b)
{ 
    return a.mProperty > b.mProperty; 
});

我想使用 lambda 函数对自定义类进行排序,而不是绑定实例方法.但是,上面的代码会产生错误:

I'd like to use a lambda function to sort custom classes in place of binding an instance method. However, the code above yields the error:

error C2564: 'const char *' : 向内置类型的函数式转换只能采用一个参数

error C2564: 'const char *' : a function-style conversion to a built-in type can only take one argument

boost::bind(&MyApp::myMethod, this, _1, _2) 配合使用效果很好.

It works fine with boost::bind(&MyApp::myMethod, this, _1, _2).

推荐答案

知道了.

sort(mMyClassVector.begin(), mMyClassVector.end(), 
    [](const MyClass & a, const MyClass & b) -> bool
{ 
    return a.mProperty > b.mProperty; 
});

我认为它会发现 > 运算符返回一个布尔值(根据文档).但显然并非如此.

I assumed it'd figure out that the > operator returned a bool (per documentation). But apparently it is not so.

相关文章