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?
+1
A:
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.
Ben Voigt
2010-06-21 04:19:56
+1
A:
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 );
xtofl
2010-06-21 11:32:59
it also has to inherit unary_function
John Smith
2010-06-21 11:44:12
You don't HAVE TO write functor, a simple function works as well.
DaClown
2010-06-21 11:45:32
You might also get somewhere using `bind2nd( mem_fun_ref( YourFHere::memberfunction ), 4 )`...
xtofl
2010-06-21 11:47:48
@John Smith: it is required for e.g. `transform` and `copy`. `for_each` doesn't need the `unary_function` members.
xtofl
2010-06-21 12:29:42