将循环转移到C++03 for each
transfer loop into C++03 for_each
可能重复:
对通过引用获取参数的方法使用bind1st
我有以下传统的C++03循环(使用auto
仅用于堆栈溢出空间效率):
for (auto it = some_vector.begin(); it != some_vector.end(); ++it)
{
foobar.method(*it);
}
在C++11中,我设法将其重写为以下for_each
调用,该调用运行良好:
std::for_each(some_vector.begin(), some_vector.end(),
std::bind(&Foobar::method, std::ref(foobar), _1));
(当然,我可以在C++11中使用lambda,但这不是重点。)不幸的是,std::bind
不是C++03的一部分,所以我尝试用std::bind1st
和std::mem_fun_ref
:模拟它
std::for_each(some_vector.begin(), some_vector.end(),
std::bind1st(std::mem_fun_ref(&Foobar::method), std::ref(foobar)));
但这触发了Visual Studio中的C2535错误("成员函数已定义或声明"):
// inside class binder1st in header xfunctional
result_type operator()(const argument_type& _Right) const
{ // apply functor to operands
return (op(value, _Right));
}
result_type operator()(argument_type& _Right) const
{ // apply functor to operands <--- ERROR C2535 HERE
return (op(value, _Right));
}
这是Visual Studio中的常量正确性错误,还是我做错了什么?
此外,std::ref
似乎不是C++03的一部分。有什么变通办法吗?
为什么不简单地使用std::mem_fun
?它期望一个指针作为第一个参数,例如:
#include <functional>
#include <algorithm>
#include <vector>
struct foo{
void method(int){}
};
int main(){
std::vector<int> v;
foo f;
std::for_each(v.begin(), v.end(),
std::bind1st(std::mem_fun(&foo::method), &f));
}
相关文章:
- C++ 中用于二维数组的 for-each 循环
- 计算 fib(n) 的次数称为 FOR EACH n
- 支持自定义 const 本机C++容器类的"for each"
- C++ for-each 语句触发"vector iterators incompatible"断言失败:this->_Getcont() == 0
- 为什么我的矢量中的项目在 C++ 中的 for-each 循环期间不会改变?
- 当循环返回"for each"项的 nullptr 时?
- 正确使用C++ 'for each'选项
- "for each"能保证使用更改数组吗?
- 基于范围的循环与 for-each 循环有何不同
- C++:从"for each"循环中的映射中删除值
- 将函数应用于std::map值,其中包含for each和lambda函数
- 正在擦除for(-each)自动循环中的项目
- g++ 4.4.7 -std=gnu++0x 应该编译"for each"结构吗?
- 将循环转移到C++03 for each
- 在 for-each 循环中使用 'auto' 时是否需要添加'const'?
- C++中的"for each"循环如何知道数组的长度
- 基本c++: for-each循环
- 如何使c++中的for each循环函数与自定义类一起工作
- 如何使用for-each循环来美化析构函数
- for-each 循环生成错误,但 for(it=begin()...在遍历 std::map 包含 unique_ptr 时不会