How to use std::foreach with parameters/modification

Jesse Beder picture Jesse Beder · Jan 24, 2009 · Viewed 22.5k times · Source

I've found myself writing

for(int i=0;i<myvec.size();i++)
   myvec[i]->DoWhatever(param);

a lot, and I'd like to compress this into a foreach statement, but I'm not sure how to get param in there without going super-verbose. I've also got things like

for(int i=0;i<myvec.size();i++)
   if(myvec[i]->IsOK())
      myvec[i]->DoWhatever(param);

and I'd like to rewrite that guy too. Any thoughts?

Oh, also, for various reasons, I don't want to use boost.

Answer

Martin York picture Martin York · Jan 24, 2009
#include <vector>
#include <algorithm>
#include <functional>

class X
{
    public:
        void doWhat(int x) {}
        bool IsOK() const {return true;}
};
class CallWhatIfOk
{
    public:
        CallWhatIfOk(int p): param(p) {}

        void operator()(X& x) const
        {   if (x.IsOK())    {x.doWhat(param);}}
    private:
        int param;
};

int main()
{
    std::vector<X>      myVec;

    std::for_each(  myVec.begin(),
                    myVec.end(),
                    std::bind2nd(std::mem_fun_ref(&X::doWhat),4)
                 );


    std::for_each(  myVec.begin(),
                    myVec.end(),
                    CallWhatIfOk(4)
                 );
}