[英]std::for_each usage on member function with two args
Here's a general idea of how my class is defined as ( it performs other operations than what is mentioned below) 以下是关于如何定义我的类的一般概念(它执行除下面提到的操作之外的其他操作)
struct Funktor
{
Funktor(int val):m_val(val){}
bool operator()(int arg1, int arg2) { return m_val==arg1*arg2; }
int m_val;
};
And now I have a vector of the above objects, and I am trying to call operator() using for_each, is there a way to do this? 现在我有一个上述对象的向量,我试图使用for_each调用operator(),有没有办法做到这一点? I know it can be done using bind2nd and mem_func_ref but when there's only one argument but for two arguments I haven't found a way.
我知道它可以使用bind2nd和mem_func_ref完成,但是当只有一个参数但是对于两个参数我没有找到方法。
int main()
{
std::vector<Funktor> funktors;
funktors.push_back(Funktor(10));
funktors.push_back(Funktor(20));
funktors.push_back(Funktor(30));
int arg1 = 5, arg2 = 6;
//instead of the for loop below I want to use for_each
for(std::vector<Funktor>::iterator itr = funktors.begin(); funktors.end() != itr; ++itr)
{
(*itr)(arg1,arg2);
}
}
Thanks for any help. 谢谢你的帮助。 Best.
最好。
CV 简历
C++03 Solution (without boost): C ++ 03解决方案(无提升):
Write another functor as: 写另一个仿函数:
struct TwoArgFunctor
{
int arg1, arg2;
TwoArgFunctor(int a, int b) :arg1(a), arg2(b) {}
template<typename Functor>
bool operator()(Functor fun)
{
return fun(arg1, arg2); //here you invoke the actual functor!
}
};
Then use it as: 然后用它作为:
std::for_each(funktors.begin(),funktors.end(), TwoArgFunctor(arg1,arg2));
C++11 Solution: C ++ 11解决方案:
std::for_each(funktors.begin(),funktors.end(),
[&] (Funktor f) -> bool { return f(arg1,arg2); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.