Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing all elements in vector(list, deque...) using C++11 Lambda functions

Tags:

c++

c++11

lambda

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 ?

like image 987
G-71 Avatar asked Nov 10 '11 18:11

G-71


1 Answers

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;
like image 64
Nawaz Avatar answered Nov 15 '22 07:11

Nawaz