Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture variable inside lambda

Tags:

c++

lambda

c++14

I have code from here:

std::sort(begin(v), end(v), [](auto const &t1, auto const &t2) {
        return get<0>(t1) < get<0>(t2); // or use a custom compare function
});

I wanted to sort tuple multiple times so I wrote this code:

int k = 10;
while(k--){
    std::sort(begin(v), end(v), [](auto const &t1, auto const &t2) {
    return get<k>(t1) < get<k>(t2); // or use a custom compare function
    });
}

but I get error error: ‘k’ is not captured. I tried to do it in this way:

int k = 10;
while(k--){
    std::sort(begin(v), end(v), [&k](auto const &t1, auto const &t2) {
    return get<k>(t1) < get<k>(t2); // or use a custom compare function
    });
}

but it is not the proper way and error error: the value of ‘k’ is not usable in a constant expression occurs.

How to capture k variable?

like image 443
Piotr Wasilewicz Avatar asked Apr 11 '18 07:04

Piotr Wasilewicz


People also ask

How do you capture a member variable in lambda C++?

To capture the member variables inside lambda function, capture the “this” pointer by value i.e. std::for_each(vec. begin(), vec. end(), [this](int element){ //.... }

Can we declare variable in lambda expression?

A lambda expression can't define any new scope as an anonymous inner class does, so we can't declare a local variable with the same which is already declared in the enclosing scope of a lambda expression. Inside lambda expression, we can't assign any value to some local variable declared outside the lambda expression.

How do you pass a local variable to lambda?

Capturing Local Variables by value inside Lambda Function To capture the local variables by value, specify their name in capture list i.e. // Local Variables std::string msg = "Hello"; int counter = 10; // Defining Lambda function and // Capturing Local variables by Value auto func = [msg, counter] () { //... };

Can lambda capture the local variable in Java?

Lambda expression in java Using a local variable is as stated. However, when a lambda expression uses a local variable from its enclosing scope, a special situation is created that is referred to as a variable capture. In this case, a lambda expression may only use local variables that are effectively final.


3 Answers

As mch said in the comment, the problem is that k is not a compile time constant.

For a compile time constant, to iterate from N to 0, you may need template and recursion:

#include <algorithm>
#include <tuple>
#include <type_traits>
#include <vector>

using namespace std; // just for simplify, and not recommended in practice

template <size_t N, typename Iterator, enable_if_t<N == 0, int> = 0>
void foo(Iterator begin, Iterator end)
{
    sort(begin, end,
        [](const auto &t1, const auto &t2) {
            return get<0>(t1) < get<0>(t2); 
        }
    );
}

template <size_t N, typename Iterator, enable_if_t<N != 0, int> = 0>
void foo(Iterator begin, Iterator end)
{
    sort(begin, end,
        [](const auto &t1, const auto &t2) {
            return get<N>(t1) < get<N>(t2); 
        }
    );
    foo<N - 1>(begin, end);
}

int main()
{
    vector<tuple<int, int>> v{{0, 1}, {0, 0}, {1, 1}};
    foo<1>(v.begin(), v.end());

    // posible results:
    // {0, 0}, {0, 1}, {1, 1}
    // {0, 1}, {0, 0}, {1, 1} // impossible if use std::stable_sort instead
}
like image 65
xskxzr Avatar answered Sep 30 '22 10:09

xskxzr


std::get only accepts a template argument which is an expression whose value that can be evaluated at compiling time. You can't use k, because it is a variable that changes value.

std::sort(begin(v), end(v), [](auto const &t1, auto const &t2) {
    const int k = 3;
    return std::get<k>(t1) < std::get<k>(t2); // or use a custom compare function
});

As I wrote in the comments, I know const int = 3 will shadow the k value outside of the lambda expression, but this example shows that get will work when it it receives a compiling time constant value. For example, if you try to set k = 5, for example where v only has 4 tuple parameters, the compiler will give an error because it knows that this is out of range.

The following code will give an error, but if k is set to 3, it will work

std::vector<std::tuple<int, int, int, int>> v;
std::sort(begin(v), end(v), [](auto const &t1, auto const &t2) {
            const int k = 5;
            return std::get<k>(t1) < std::get<k>(t2); // or use a custom compare function
        });
like image 33
Arkady Godlin Avatar answered Sep 30 '22 09:09

Arkady Godlin


#include <tuple>
#include <utility>
#include <cstddef>
#include <algorithm>
#include <cstddef>
#include <iterator>

template <std::size_t I, typename It, typename F>
void sort_tuple(It it, It end, F f)
{
    std::stable_sort(it, end, [f](const auto& t1, const auto& t2)
    {
        return f(std::get<I>(t1), std::get<I>(t2));
    });
}

template <typename It, typename F, std::size_t... Is>
void sort_tuple(It it, It end, F f, std::index_sequence<Is...>)
{
    int dummy[] = { 0, (sort_tuple<sizeof...(Is) - Is - 1>(it, end, f), 0)... };
    static_cast<void>(dummy);
}

template <typename It, typename F>
void sort_tuple(It it, It end, F f)
{
    sort_tuple(it, end, f, std::make_index_sequence<
            std::tuple_size<typename std::iterator_traits<It>::value_type>::value
                           >{});
}

Test:

std::vector<std::tuple<int, int, int>> v{ {2,1,2}, {2,2,2}, {3,2,1}
                                        , {1,1,1}, {1,2,1}, {2,2,1} };

sort_tuple(begin(v), end(v), [](const auto& t1, const auto& t2)
{
    return t1 < t2;
});

for (auto& t : v)
{
    std::cout << std::get<0>(t) << " " << std::get<1>(t) << " " << std::get<2>(t) << std::endl;
}

DEMO

like image 22
Piotr Skotnicki Avatar answered Sep 30 '22 10:09

Piotr Skotnicki