The classical example using STL algorithms:
void foo(int){};
vector<int> collection;
collection.push_back(3);
collection.push_back(4);
... etc.
std::for_each(collection.begin(), collection.end(), bind(foo, _1));
But what if we have more then one function, which needs to be called with the same argument values:
void bar(int){};
void beer(int){};
... etc.
Repeating for_each algorithm every time with different functions is not option. I need more elegant solution.
Since you tagged the question with
C++11, then you can use lambda as:I recall that C++11 has
std::beginandstd::endas free functions, which should be preferred over the member functions:The rationale why the free functions should be preferred is because now if, for example, you change the type of the collection to simple array (say,
int collection[100]), then the above code would work just fine without changing a single character. With the new Standard C++, the free functions are going to be used more uniformly than the member functions.Or, you can use range-based
forloop as:Ah! It looks even better. Neat and clean, with no
beginandendat all.