I have the following code:
#include <iostream>
#include <vector>
#include <algorithm>
int main( int argc, char* argv[] )
{
std::vector< int > obj;
obj.push_back( 10 );
obj.push_back( 20 );
obj.push_back( 30 );
std::for_each( obj.begin(), obj.end(), []( int x )
{
return x + 2;
} );
for( int &v : obj )
std::cout << v << " ";
std::cout << std::endl;
return 0;
}
The result is : 10, 20, 30
i want to change all elements in vector (obj), using Lambda functions of new C++11 standard.
This is the code of implementation for_each function:
template<class InputIterator, class Function>
Function for_each(InputIterator first, InputIterator last, Function f)
{
for ( ; first!=last; ++first )
f(*first);
return f;
}
*first passed by value and cope of element is changed, what is the alternative of for_each i must use that i have a result: 12, 22, 32 ?
You’ve to do this :
In your (not my) code, the return type of the lambda is deduced as
int, but the return value is ignored as nobody uses it. That is why there is no return statement in my code, and the return type is deduced asvoidfor this code.By the way, I find the range-based
forloop less verbose thanstd::for_eachfor this purpose: