有一个类和事件结构:
struct Foo
{
Foo(): name("nx"), val(9) {}
string name;
int val;
};
class Base
{
public:
Base()
{
/*array.push_back(Foo());
array.push_back(Foo());
array.push_back(Foo()); //fill array Foo
array.push_back(Foo());
array.push_back(Foo());*/
}
void Define(Foo* desktop)
{
cout << desktop->name << " " << desktop->val << "\n";
}
void Oblem()
{
/*for(int i = 0; i < array.size(); ++i)
{
Define(&array[i]);
}*/
for_each(array.begin(), array.end(), mem_fun_ref(&Base::Define));
}
public:
std::vector<Foo> array;
};
如何在算法for_each?
上替换注释掉的循环我现在有这些错误:
答案 0 :(得分:2)
Base::Define
有两个参数:Foo* desktop
和隐式Base* this
。您需要绑定this
中的当前Oblem
以获取仅需Foo
的函数。此外,Define
应将其参数设为Foo& desktop
(或者更好,如果这是真实代码Foo const& desktop
)。
使用TR1中的标准功能(或Boost实现)的完整解决方案将是:
void Define(Foo const& desktop) const
{
cout << desktop.name << " " << desktop.val << "\n";
}
void Oblem() const
{
for_each(
array.begin(), array.end()
, std::bind( &Base::Define, this, _1 )
);
}
答案 1 :(得分:2)
class Base
{
public:
Base() : array(5) {}
void Define(Foo &desktop)
{
cout << desktop.name << " " << desktop.val << "\n";
}
void Oblem()
{
for_each(array.begin(),array.end(),[this](Foo &f) {
Define(f);
});
// or
for_each(array.begin(),array.end(),
bind(&Base::Define,this,placeholders::_1));
}
public:
std::vector<Foo> array;
};