我有一张地图如下:
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::==‘类型的左操作数(或者没有可接受的转换)
我花了将近两个小时来尝试不同的方法,试图让它发挥作用,因为我在过去写过类似的lambda函数,这些函数都是按预期编译和工作的。为什么会发生这种情况?
发布于 2014-09-16 18:21:15
首先,必须使用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; });发布于 2014-09-16 18:11:57
它应该是
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_type是std::pair<const int, std::unique_ptr<Person>>。
编辑:正如其他人所指出的,接受谓词的是std::find_if。
发布于 2014-09-16 18:13:43
映射的基础迭代器类型不是std::unique_ptr<Person>。但是std::pair<int, std::unique_ptr<Person>>。
您需要修改lambda以获得正确的论点。
[&](const std::pair<const int, std::unique_ptr<Person>>& pair)并比较从对中提取第二个值。
return pair.second->getName() == _name;您还应该使用std::find_if,因为它接受UnaryPredicate而不仅仅是值。
https://stackoverflow.com/questions/25875673
复制相似问题