我只想知道如何在 lambda 表达式捕获括号内编写对。 因为以下代码无法编译,所以我遗漏了一些东西......
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
最佳答案
[iter.first]( const std::string& str )->bool { return str == iter.first; }
// ^^^^^^^^^^
Lambda 捕获用于标识符,不适用于任意表达式或其他任何东西。
只要传入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. [..]
关于c++ - std::pair 在 lambda 表达式中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19790451/