Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Structured binding in lambda arguments

Why I cannot use C++17 structured binding in this case?

std::map<int, int> m;
std::find_if( m.cbegin(), m.cend(), []( const auto & [x, y] ){ return x == y; } );
like image 427
Kill KRT Avatar asked Aug 01 '19 10:08

Kill KRT


1 Answers

Structured binding works only with initializers. You need to have a particular object which you can bind to. Your lambda makes closure which will be called with different instances of pair of map. The place when you can use structured bindings is inside lambda body - you have a pair which you can refer to.

std::find_if( m.cbegin(), m.cend(), []( const auto & p ){ 
    const auto& [x,y] = p;
    return x == y; 
}); 
like image 89
rafix07 Avatar answered Sep 19 '22 21:09

rafix07