tags:

views:

191

answers:

2

Hello, I have constructed a map and loaded it with data. If I iterate over all the elements I see they are all valid. However, the find method doesn't find my item. I'm sure it's something stupid I am doing. Here is 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 :(

+14  A: 

Since the key is char*, they will be compared by address, not by value, e.g.

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

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

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

(And probably you want to use a Person or shared_ptr<Person> as the value to avoid memory leak.)

KennyTM
I...am an idiot....Thanks Kenny! It works fine with std::string
Joe
The key shouldn't be const (if you mean `const string`). Map will automatically make it const itself. If you mean using `char*` as the key, then yes, the map would make the pointer const, but you'd still be able to modify the string itself, thus blowing everything up.
UncleBens
+2  A: 

The alternative to KennyTM's solution (std::string, which is really the better solution) is to tell map that it needs to use strcmp(), not <. However, the return value of strcmp() isn't what std::map expects, it wants a boolean. So you need a thin wrapper function : return strcmp(a,b) < 0;

MSalters