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
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 );
4 Comments
John Smith
it also has to inherit unary_function
DaClown
You don't HAVE TO write functor, a simple function works as well.
xtofl
You might also get somewhere using
bind2nd( mem_fun_ref( YourFHere::memberfunction ), 4 )...xtofl
@John Smith: it is required for e.g.
transform and copy. for_each doesn't need the unary_function members.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.