在STL容器中使用boost::lambda
Using boost::lambda with an STL container
完整代码见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]; });
相关文章:
- VS Code C++:不准确的系统包括路径错误(wchar.h,boost/lambda/lambda.hpp)
- How can I std::sqrt(boost::lambda::placeholder1_type)?
- ref() in Boost::Lambda?
- 在 boost::lambda 中表达 _1.second->pair().first == r
- 正在从带有参数的new_ptr的boost::lambda::bind中获取boost::函数
- 如何使用Boost(Lambda?)使std::sort()更容易
- 在 boost::lambda 中使用 static_cast
- Using boost::lambda with boost::thread
- boost::lambda std::map
- boost::bind in boost::lambda 的嵌套用法不起作用
- MSVC和boost::lambda::绑定错误:T0:不允许使用标准参数
- Boost lambda函数调用
- 使用boost lambda构造创建初始化的智能ptr的容器
- 无法转换 boost::lambda::..到长无符号的 int
- C++boost lambda和===-运算符的问题
- 在STL容器中使用boost::lambda
- boost::bind、boost::lambda::bind和boost::phoenix::bind的区别
- 使用boost::lambda或boost::phoenix与std::find_if
- 将boost::lambda::bind的返回值赋给object
- Boost lambda::_1 in C++ 0x