C++ passing a lambda return value to a function

There is a function that simply outputs numbers from a vector.

void test(std::vector<int> vec)
{
    for(int item: vec)
        std::cout << item << std::endl;
}

There is a vector:

std::vector<int> vec = {1, 2, 3};

I want to pass a copy of this vector to the function, which will have all the elements greater than 1. I did it like this:

int main()
{
    std::vector<int> vec = {1, 2, 3};
    std::vector<int> temp;
    for(int item: vec)
        vec.push_back(item + 1);
    test(temp);
    return 0;
}

So far, there are no problems, but how do I try to do it through the lambda:

int main()
{
    std::vector<int> vec = {1, 2, 3};
    test([vec]() {
        std::vector<int> temp;
        for(int item: vec)
            temp.push_back(item + 1);
        return temp;
    });
    return 0;
}

Catching an error:

Could not convert ‘main()::{std::vector(vec)}’ from ‘main()::’ to ‘std::vector

I understand that as an argument the lambda itself is passed, but how to pass what it returns?

Author: Harry, 2020-04-25

1 answers

You should not pass the lambda itself, but the result of its call!...

        return temp;
    }());
    return 0;
}

Note the () at the end of the lambda...

But I prefer the option of passing the vector rather than capturing it.

test([](const std::vector<int>& vec) {
    std::vector<int> temp;
    for(int item: vec)
        temp.push_back(item + 1);
    return temp;
}(vec));

And even more - without any extra vector at all:

void test(std::vector<int>& vec, std::function<int(int)> f)
{
    for(int item: vec)
        std::cout << f(item) << std::endl;
}

int main()
{
    std::vector<int> vec = {1, 2, 3};

    test(vec,[](int i) { return i+1; });
    return 0;
}

No intermediate vectors... And in test, a reference is passed, not a copy, because of the value-based transfer :)

 4
Author: Harry, 2020-04-25 13:21:04