首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >科技促进发展方面的Lambda问题::查找

科技促进发展方面的Lambda问题::查找
EN

Stack Overflow用户
提问于 2014-09-16 18:08:08
回答 3查看 2.2K关注 0票数 1

我有一张地图如下:

代码语言:javascript
复制
std::map<int, std::unique_ptr<Person>> ratingMap;

我希望创建一个函数,该函数接受字符串参数_name并遍历映射,直到找到同名的人:

代码语言:javascript
复制
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::==‘类型的左操作数(或者没有可接受的转换)

我花了将近两个小时来尝试不同的方法,试图让它发挥作用,因为我在过去写过类似的lambda函数,这些函数都是按预期编译和工作的。为什么会发生这种情况?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2014-09-16 18:21:15

首先,必须使用std::find_if 而不是 std::find,并修复lambda的参数类型。

代码语言:javascript
复制
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; });
票数 1
EN

Stack Overflow用户

发布于 2014-09-16 18:11:57

它应该是

代码语言:javascript
复制
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; });

因为map::value_typestd::pair<const int, std::unique_ptr<Person>>

编辑:正如其他人所指出的,接受谓词的是std::find_if

票数 8
EN

Stack Overflow用户

发布于 2014-09-16 18:13:43

映射的基础迭代器类型不是std::unique_ptr<Person>。但是std::pair<int, std::unique_ptr<Person>>

您需要修改lambda以获得正确的论点。

代码语言:javascript
复制
[&](const std::pair<const int, std::unique_ptr<Person>>& pair)

并比较从对中提取第二个值。

代码语言:javascript
复制
return pair.second->getName() == _name;

您还应该使用std::find_if,因为它接受UnaryPredicate而不仅仅是值。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25875673

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档