C++ STL map.find()找不到我的东西

Joe*_*Joe 4 c++ stl map find

我构建了一个地图并用数据加载它.如果我遍历所有元素,我看到它们都是有效的.但是,find方法找不到我的项目.我确定这是我做的蠢事.这是片段:

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

...
Run Code Online (Sandbox Code Playgroud)

...后来....

_mapIter = _myMap.find(firstName); // returns map.end
_mapIter = _myMap.find("joe"); // returns map.end
Run Code Online (Sandbox Code Playgroud)

我不明白为什么:(

ken*_*ytm 14

由于密钥是char*,它们将按地址而不是按值进行比较,例如

char* a = "123";
char* b = new char[4];
memcpy(b, a, 4);
assert(a != b);
Run Code Online (Sandbox Code Playgroud)

您应该使用a std::string,它具有重载<值以进行值比较.

typedef std::map<std::string, Person*> mapType;
...
Run Code Online (Sandbox Code Playgroud)

(可能你想使用Personshared_ptr<Person>作为值来避免内存泄漏.)