std::find中的Lambda问题
Lambda issue in std::find
我有一个如下的映射:
std::map<int, std::unique_ptr<Person>> ratingMap;
我想创建一个函数,该函数使用字符串参数_name并遍历映射,直到它找到一个同名的人:
void Person::deleteFromMap(const std::string& _name){
//Searches the map for a person whose name is the same as the argument _name
auto found = std::find(ratingMap.begin(), ratingMap.end(),
[&](const std::unique_ptr<Person>& person) -> bool{return person->getName() == _name; });
然而,这拒绝编译并给出以下错误:
错误1错误C2678:二进制"==":找不到接受类型为"std::pair"的左侧操作数的运算符(或者没有可接受的转换)
我花了将近两个小时尝试它的变体,试图让它发挥作用,因为我在过去写过类似的lambda函数,这些函数已经按预期编译和工作。为什么会发生这种情况?
应该是
void Person::deleteFromMap(const std::string& _name){
//Searches the map for a person whose name is the same as the argument _name
auto found = std::find_if(ratingMap.begin(), ratingMap.end(),
[&](std::pair<const int, std::unique_ptr<Person>>& p) -> bool{return p.second->getName() == _name; });
因为CCD_ 1是CCD_。
EDIT:正如其他人所指出的,是std::find_if
接受谓词。
映射的底层迭代器类型不是std::unique_ptr<Person>
。而CCD_ 5。
您需要修改lambda以采用正确的参数
[&](const std::pair<const int, std::unique_ptr<Person>>& pair)
并从比较中的对中提取第二值
return pair.second->getName() == _name;
您还应该使用std::find_if
,因为它接受UnaryPredicate,而不仅仅是值
首先,必须使用std::find_if
而不是std::find
,并修复lambda的参数类型。
auto found = std::find_if(ratingMap.begin(), ratingMap.end(),
// ^^^
[&](const std::pair<const int, std::unique_ptr<Person>>& person) -> bool
{ return person.second->getName() == _name; });
相关文章:
- Lambda 捕获条款的问题
- 在使用 std::sort() 和 lambda 函数按属性对 ADT 的向量进行排序时遇到问题
- 与lambda一起使用虚拟继承在初始化列表中捕获此问题的GCC错误
- 关于Lambda超载,输入转换和完美转发的问题
- lambda函数的C++问题
- 这种递归多态 C++1y lambda 调用有什么问题?
- C++Lambda函数关闭-内存问题
- 使用C++11 lambda函数将点击事件连接到函数时出现问题
- 我的 lambda 表达式进行映射键比较有什么问题?
- 奇怪的lambda问题(编译器错误?
- 在 C++ 中使用 Lambda 表达式和 auto 关键字时出现问题
- 将 lambda 转换为 std::函数时出现问题
- 嵌套Lambda捕获问题
- C++:lambda函数和捕获列表的问题
- std::find中的Lambda问题
- C++boost lambda和===-运算符的问题
- 使用std::bind在lambda中捕获std::unique_ptr时出现问题
- 将lambda传递给模板类中的方法(头文件/源文件问题)
- 这种使用 boost::lambda::bind 有什么问题?
- 模板化函数接受lambda问题