【问题标题】:Lambda issue in std::findstd::find 中的 Lambda 问题
【发布时间】:2014-09-17 02:22:40
【问题描述】:

我有一张地图如下:

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 函数,像这样编译并按预期工作。为什么会这样?

【问题讨论】:

标签: c++ c++11 lambda find stdmap


【解决方案1】:

应该是

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&lt;const int, std::unique_ptr&lt;Person&gt;&gt;

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

【讨论】:

  • 我已经编辑了我的代码,它完全一样,但我仍然得到同样的东西:错误 C2678: 二进制 '==' : 找不到运算符,它的左手操作数为type 'std::pair' (或没有可接受的转换)
  • @Bluejay:已修复。我没有看到代码中的第二个错误。
【解决方案2】:

您的地图的基础迭代器类型不是std::unique_ptr&lt;Person&gt;。但是std::pair&lt;int, std::unique_ptr&lt;Person&gt;&gt;

您需要修改您的 lambda 以采用正确的参数

[&](const std::pair<const int, std::unique_ptr<Person>>& pair)

并从比较中提取第二个值

return pair.second->getName() == _name;

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

【讨论】:

    【解决方案3】:

    首先,你必须使用std::find_if not 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; });
    

    【讨论】:

    • 谢谢,成功了。我最初在原始代码中使用 find_if 并认为我这样做是错误的,结果证明参数类型从一开始就是罪魁祸首。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-31
    • 1970-01-01
    • 2022-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多