我想保存自己一些打字,因此定义如下:
using namespace std;
vector<MyClass> vec;
auto vecsort = bind(sort,vec.begin(),vec.end(),[] (MyClass const &a,MyClass const &b) {
// custom comparison function
});
vecsort(); // I want to use vecsort() a lot afterwards
由于某种原因,这不能编译 – 为什么?
使用boost不是一个选项.
最小工作实例:
#include <vector>
#include <utility>
#include <algorithm>
#include <functional>
using namespace std;
int main() {
vector<pair<int,int>> vec;
for (int i = 0; i < 10; i++)
vec.push_back(make_pair(10 - i,0));
auto vecsort = bind(sort,[] (pair<int,int> const &a,pair<int,int> const &b) {
return a.first < b.first;
});
vecsort();
}
错误:
error: no matching function for call to 'bind(<unresolved overloaded function type>,std::vector<std::pair<int,int> >::iterator,main()::__lambda0)'
解决方法
问题是std :: sort不是一个函数对象.它是一个功能模板.处理问题的最简单的方法是创建一个简单的包装器对象:
struct sorter {
template <typename RndIt,typename Cmp>
void operator()(RndIt begin,RndIt end,Cmp cmp) {
std::sort(begin,end,cmp);
}
};
现在可以使用
std::bind(sorter(),[](...){ ... });