std::find中的Lambda问题

Lambda issue in std::find

本文关键字:问题 Lambda find std 中的      更新时间:2023-10-16

我有一个如下的映射:

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