用两个参数在成员函数上使用std :: for_each [英] std::for_each usage on member function with two args
问题描述
struct 这是一个关于如何定义我的类的一般概念(它执行的操作不是下面提到的) Funktor
{
Funktor(int val):m_val(val){}
bool operator()(int arg1,int arg2){return m_val == arg1 * arg2; }
int m_val;
};
现在我有一个上述对象的向量,我试图调用operator() for_each,有没有办法做到这一点?我知道这可以使用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;
//而不是for循环下面我想使用for_each
(std :: vector< Funktor> :: iterator itr = funktors.begin(); funktors.end()!= itr; ++ itr)
{
(* itr)(arg1,arg2);
$ b感谢您的帮助。
CV
解决方案 boost:)
写另一个函数为:
$ b $ $ $ $ $ $ $ $ struct struct TwoArgFunctor
{
int arg1,arg2;
TwoArgFunctor(int a,int b):arg1(a),arg2(b){}
模板< typename Functor>
bool operator()(Functor fun)
{
return fun(arg1,arg2); //在这里你调用实际函子!
}
};
然后使用它:
<$ p $ (funktors.begin(),funktors.end(),TwoArgFunctor(arg1,arg2));
C ++ 11解决方案:
std :: for_each(funktors.begin(),funktors.end(),
[&](Funktor f) - > bool {return f(arg1,arg2);});
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? 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.
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):
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:
std::for_each(funktors.begin(),funktors.end(),
[&] (Funktor f) -> bool { return f(arg1,arg2); });
这篇关于用两个参数在成员函数上使用std :: for_each的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!