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 ?
i want to change all elements in vector (obj), using Lambda functions of new C++11 standard.
You've to do this :
std::for_each( obj.begin(), obj.end(), [](int & x)
{ //^^^ take argument by reference
x += 2;
});
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 as void
for this code.
By the way, I find the range-based for
loop less verbose than std::for_each
for this purpose:
for( int &v : obj ) v += 2;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With