Mind-boggling.
The std::for_each
http://www.cplusplus.com/reference/algorithm/for_each/ is a convenience algorithm.
You can hide/reuse the body of a loop with it:
1 2
|
for_each( myvector.begin(), myvector.end(), somethingcomplex );
for_each( a, a+5, somethingcomplex );
|
It is clear and compact that something is done for/with those arrays.
Alas, you obviously have to consult the implementation of 'somethingcomplex' to know what those loops do.
The lambda allows you write the body of somethingcomplex
in place. That does not quite make sense with for_each.
1 2 3 4 5 6 7 8 9 10 11 12 13
|
void somethingcomplex(T e) {
// 100 lines
}
for_each( myvector.begin(), myvector.end(), somethingcomplex );
// OR
for( auto it = myvector.begin(); it != myvector.end(), ++it ) {
// 100 lines
}
// OR
for_each( myvector.begin(), myvector.end(), [](T e) {
// 100 lines
} );
|
Lambdas appeared in C++11. So did ranged for-syntax.
The latter is syntactic sugar for repeating operation
for each element in array/container.
You can still use your functor to hide the body:
1 2 3
|
for ( auto e : myvector ) {
somethingcomplex( e );
}
|
However, simple stuff can be there directly:
1 2 3 4 5 6
|
for ( auto p : pokemon_to_add ) {
pokemon.push_back( p );
}
for ( auto p : pokemon ) {
std::cout << p << '\n';
}
|
There is an additional benefit in the insert(): addition of multiple elements may cause reallocation in the vector and in worst case multiple times. The insert() can do pre-emptive reallocation.
Therefore, you should really compare:
1 2 3 4 5 6
|
pokemon.insert(pokemon.end(), pokemon_to_add, pokemon_to_add + 3);
// with
pokemon.reserve( pokemon.size() + 3 );
for ( auto p : pokemon_to_add ) {
pokemon.push_back( p );
}
|