Search code examples
c++c++17structured-bindings

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; } );

Solution

  • 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; 
    });