I have a map as follows:
std::map<int, std::unique_ptr<Person>> ratingMap;
I want to create a function that takes a string argument _name and iterates through the map until it finds a person with the same 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; });
However, this refuses to compile and gives the following error:
Error 1 error C2678: binary '==' : no operator found which takes a left-hand operand of type 'std::pair' (or there is no acceptable conversion)
I've spent close to two hours trying variations of this in an attempt to get it to work, because I've written similar lambda functions in the past like this that have compiled and worked as expected. Why is this happening?
It should be
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; });
as map::value_type
is std::pair<const int, std::unique_ptr<Person>>
.
EDIT : And as noted by other, it is std::find_if
which takes the predicate.
Underlying iterator type for your map is not std::unique_ptr<Person>
. but std::pair<int, std::unique_ptr<Person>>
.
You need to modify your lambda to take correct argument
[&](const std::pair<const int, std::unique_ptr<Person>>& pair)
and extract second value from the pair in comparison
return pair.second->getName() == _name;
You should also use std::find_if
As it accepts UnaryPredicate instead of just value
First of all, you must use std::find_if
not std::find
, and fix the argument type of your 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; });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.