BTR*_*BTR 111 c++ sorting lambda const char
sort(mMyClassVector.begin(), mMyClassVector.end(),
[](const MyClass & a, const MyClass & b)
{
return a.mProperty > b.mProperty;
});
Run Code Online (Sandbox Code Playgroud)
我想使用lambda函数来排序自定义类来代替绑定实例方法.但是,上面的代码会产生错误:
错误C2564:'const char*':对内置类型的函数式转换只能接受一个参数
它工作得很好boost::bind(&MyApp::myMethod, this, _1, _2).
BTR*_*BTR 129
得到它了.
sort(mMyClassVector.begin(), mMyClassVector.end(),
[](const MyClass & a, const MyClass & b) -> bool
{
return a.mProperty > b.mProperty;
});
Run Code Online (Sandbox Code Playgroud)
我假设它弄清楚>运算符返回了一个bool(每个文档).但显然事实并非如此.
Adr*_*ian 13
要使用更多代码,您可以像这样使用它:
#include<array>
#include<functional>
int main()
{
std::array<int, 10> vec = { 1,2,3,4,5,6,7,8,9 };
std::sort(std::begin(vec ), std::end(vec ), [](int a, int b) {return a > b; });
for (auto item : vec)
std::cout << item << " ";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
将"vec"替换为您的班级,就是这样.
问题可能出在“ a.mProperty> b.mProperty”行中吗?我有以下代码可以工作:
#include <algorithm>
#include <vector>
#include <iterator>
#include <iostream>
#include <sstream>
struct Foo
{
Foo() : _i(0) {};
int _i;
friend std::ostream& operator<<(std::ostream& os, const Foo& f)
{
os << f._i;
return os;
};
};
typedef std::vector<Foo> VectorT;
std::string toString(const VectorT& v)
{
std::stringstream ss;
std::copy(v.begin(), v.end(), std::ostream_iterator<Foo>(ss, ", "));
return ss.str();
};
int main()
{
VectorT v(10);
std::for_each(v.begin(), v.end(),
[](Foo& f)
{
f._i = rand() % 100;
});
std::cout << "before sort: " << toString(v) << "\n";
sort(v.begin(), v.end(),
[](const Foo& a, const Foo& b)
{
return a._i > b._i;
});
std::cout << "after sort: " << toString(v) << "\n";
return 1;
};
Run Code Online (Sandbox Code Playgroud)
输出为:
before sort: 83, 86, 77, 15, 93, 35, 86, 92, 49, 21,
after sort: 93, 92, 86, 86, 83, 77, 49, 35, 21, 15,
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
129390 次 |
| 最近记录: |