C ++ STL map.find () doesn't find my stuff

I built a map and loaded it with data. If I repeat all the elements that I see, they are all valid. However, the find method does not find my element. I'm sure this is something stupid that I do. Here is a snippet:

// definitions // I am inserting a person class and using the firstname as the key typedef std::map<char*,Person *> mapType; mapType _myMap; mapType::iterator _mapIter; ... Person *pers = new Person(FirstName, LastName, Address, Phone); _myMap.insert(make_pair(pers->firstName, pers); ... 

... later....

 _mapIter = _myMap.find(firstName); // returns map.end _mapIter = _myMap.find("joe"); // returns map.end 

and I have no idea why :(

+4
source share
2 answers

Since the key is char* , they will be compared by address, and not by value, for example.

 char* a = "123"; char* b = new char[4]; memcpy(b, a, 4); assert(a != b); 

You should use std::string , which has an overloaded < for comparison by value.

 typedef std::map<std::string, Person*> mapType; ... 

(You probably want to use Person or shared_ptr<Person> as a value to avoid memory leaks.)

+14
source

An alternative to KennyTM's solution (std :: string, which is really the best solution) is to tell the map that it needs to use strcmp() , not < . However, the return value of strcmp() does not match the expected std::map , it wants to have a boolean value. Therefore, you need a subtle wrapper function: return strcmp(a,b) < 0;

+2
source

Source: https://habr.com/ru/post/1309771/


All Articles