1

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?

1

3 Answers 3

8

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I've edited my code and it is exactly as so, yet I am still getting the same thing: error C2678: binary '==' : no operator found which takes a left-hand operand of type 'std::pair<const _Kty,_Ty>' (or there is no acceptable conversion)
@Bluejay: Fixed. I didn't see the second error in the code.
2

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

Comments

1

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

1 Comment

Thanks, this did it. I was initially using find_if with my original code and thought that I was mistaken in doing so, turns out the argument type was the culprit from the start.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.