John Smith
John Smith

Reputation: 12797

How to use for_each with the function as the overloaded operator()

I have a std::vector of function objects. Each object can take an int, so I can say obj(4) and get an int result. How can I use the algorithm for_each to work on each element of the vector?

Upvotes: 0

Views: 325

Answers (2)

xtofl
xtofl

Reputation: 41509

You would have to create a functor 'calling' each object:

struct Caller {
  int value;
  void operator()( const YourFunctorHere& f ) const {
    f( value );
  }
} caller;
std::for_each( functors.begin(), functors.end(), caller );

Upvotes: 1

Ben Voigt
Ben Voigt

Reputation: 283614

Which version of C++? C++0x Lambdas make this short and sweet.

In C++03, for loop will be simpler than for_each.

To use for_each in C++03, you need to create a functor that stores all the input arguments in member variables and pass it to for_each. Each functor in the vector will be passed to this visitor functor as an argument, you then need to call its operator() with the stored arguments.

Upvotes: 1

Related Questions