在STL容器中使用boost::lambda

Using boost::lambda with an STL container

本文关键字:boost lambda STL      更新时间:2023-10-16

完整代码见https://gist.github.com/1341623

我想对另一个向量的索引数组(或向量)进行排序,使数组按照另一个向量的索引排序。但是,vector::at的类型无法解析。

我做了如下尝试:

OK

sort(v.begin(), v.end());

我想根据数组对索引进行排序,但是占位符不能重载operator[]

sort(index,index+10, a[_1] < a[_2]);

但是,它们重载了operator+和operator*

sort(index,index+10, *(a+_1) < *(a+_2));

我想根据向量对索引进行排序,但是编译器无法解析' vector::at'的类型。

sort(index,index+10,
  bind(&(vector<int>::at), &v, _1) < bind(&(vector<int>::at), &v, _2));
// error: no matching function for call
// to ‘bind(<unresolved overloaded function type>, ...

在网上搜索后,我发现我必须指定重载的方法类型,但编译器仍然说它无法解析该类型。

sort(index,index+10,
   bind(&static_cast<const int (*)(size_t)>(vector<int>::at), &v, _1)
 < bind(&static_cast<const int (*)(size_t)>(vector<int>::at), &v, _2));
// error: invalid static_cast from type ‘<unresolved overloaded function type>’
// to type ‘const int (*)(size_t)’ ...

我试图得到我想要的vector::at的版本,但是转换似乎失败了。

vector<int>::const_reference (*vector_int_at)(vector<int>::size_type)(vector<int>::at);
sort(index,index+10,
  bind(&vector_int_at, &v, _1) < bind(&vector_int_at, &v, _2));
// error: no matches converting function ‘at’ to type ‘const int& (*)(size_t)’ ...

这个问题我能做什么?还是我误解了什么?

请记住,指向成员函数的指针和指向自由函数的指针具有不同的类型。试一试:vector<int>::const_reference (vector<int>::*vector_int_at)(vector<int>::size_type) const = &vector<int>::at;

我通常只是声明一个转发函数,以避免与这类事情相关的各种蠕虫:

int vector_at(vector<int> const * v, size_t index) { return v->at(index); }
...
sort(index, index+10, bind(vector_at, &v, _1) < bind(vector_at, &v, _2));

为什么不使用lambda?

sort(index, index+10, [&a](int i, int j) { return a[i] < a[j]; });