How can you call a Function over some part of a container, using for_each() ?
I have created a for_each_if() to do a
for( i in shapes )
if( i.color == 1 )
displayShape(i);
and the call looks like
for_each_if( shapes.begin(), shapes.end(),
bind2nd( ptr_fun(colorEquals), 0 ),
ptr_fun( displayShape ) );
bool colorEquals( Shape& s, int color ) {
return s.color == color;
}
However, I feel immitating STL-like algorithms is not something that I should be doing.
-
Is there a way to use only existing STL keywords to produce this ?
I did not want to do a
for_each( shapes.begin(), shapes.end(), bind2nd( ptr_fun(display_shape_if_color_equals), 0 ) );because, in a more complicated case, the functor name would be misleading with respect to what the functor
-
*Is there a way to access a struct’s member (like
colorEquals) for functions likefor_eachwithout having to create a function ? *
To use a regular for_each with an if you would need a Functor that emulates an if condition.
Unfortunately my template hackery isn’t good enough to manage this with bind1st and bind2nd as it somehow gets confusing with the binder being returned being a
unary_functionbut it looks pretty good withboost::bindanyhow. My example is no means perfect as it doesn’t allow the Func passed into if_fun to return and I guess somebody could point out more flaws. Suggestions are welcome.