Athanase
Athanase

Reputation: 943

std::pair in lambda expression

I just want to know how to write pairs inside the lambda expression capture brackets. Because the following code does not compile so I'm missing something ...

std::vector<std::pair<std::string, std::string>> container1_;

for( auto iter : container1_ )
{
    auto result = std::find_if( container2_.cbegin(), container2_.cend(),
        [iter.first]( const std::string& str )->bool { return str == iter.first; } );
}

In member function ‘bool MsgChecker::CheckKeys()’:
error: expected ‘,’ before ‘.’ token
error: expected identifier before ‘.’ token

Upvotes: 3

Views: 2766

Answers (1)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385194

  [iter.first]( const std::string& str )->bool { return str == iter.first; }
// ^^^^^^^^^^

Lambda captures are for identifiers, not for arbitrary expressions or anything else.

Just pass in iter:

  [iter]( const std::string& str )->bool { return str == iter.first; }

[C++11: 5.1.2/1]:

[..]

 capture:
   identifier
   & identifier
   this

[C++11: 2.11/1]: An identifier is an arbitrarily long sequence of letters and digits. [..]

Upvotes: 9

Related Questions