I have a collection of elements that I need to operate over, calling member functions on the collection:
std::vector<MyType> v; ... // vector is populated
For calling functions with no arguments it’s pretty straight-forward:
std::for_each(v.begin(), v.end(), std::mem_fun(&MyType::myfunc));
A similar thing can be done if there’s one argument to the function I wish to call.
My problem is that I want to call a function on elements in the vector if it meets some condition. std::find_if returns an iterator to the first element meeting the conditions of the predicate.
std::vector<MyType>::iterator it = std::find_if(v.begin(), v.end(), MyPred());
I wish to find all elements meeting the predicate and operate over them.
I’ve been looking at the STL algorithms for a ‘find_all‘ or ‘do_if‘ equivalent, or a way I can do this with the existing STL (such that I only need to iterate once), rather than rolling my own or simply do a standard iteration using a for loop and comparisons.
Boost Lambda makes this easy.
You could even do away with defining MyPred(), if it is simple. This is where lambda really shines. E.g., if MyPred meant ‘is divisible by 2’:
Update: Doing this with the C++0x lambda syntax is also very nice (continuing with the predicate as modulo 2):
At first glance this looks like a step backwards from boost::lambda syntax, however, it is better because more complex functor logic is trivial to implement with c++0x syntax… where anything very complicated in boost::lambda gets tricky quickly. Microsoft Visual Studio 2010 beta 2 currently implements this functionality.