0

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?

2 Answers 2

1

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 );
Sign up to request clarification or add additional context in comments.

4 Comments

it also has to inherit unary_function
You don't HAVE TO write functor, a simple function works as well.
You might also get somewhere using bind2nd( mem_fun_ref( YourFHere::memberfunction ), 4 )...
@John Smith: it is required for e.g. transform and copy. for_each doesn't need the unary_function members.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.