Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::map find not working in C++ [duplicate]

I have created a hash map and an iterator using the below lines:

std::map<const char*,vaLueClass *> myCache;
std::map<const char*,vaLueClass *>::iterator myCacheIterator;

Then I insert into this map using the below line:

myCache[anotherObject->getStringKey()] = new vaLueClass(anotherObj1->getIntAttr(), anotherObj1-->getIntAttr());

Then whenever I tried to search if an ENTRY for a particular string exist in this map or nut using below lines, it always enters the IF block which in other words it does not find any entries inside this map.

myCacheIterator= myCache.find(sampleObject->getstringKey());

NOTE: here sampleObject->getstringKey() returns the same key which has been inserted earlier.

if (myCacheIterator.operator ==(myCache.end())){
   // this block means that no matched entry is found inside the map myCache
}

Also, is this the proper way to create and use std::map in C++ ? If not then please suggest one.

Also, I have not used the keyword new to create the std::map object.

like image 542
user3243499 Avatar asked Dec 14 '22 08:12

user3243499


1 Answers

In a std::map, the keys are compared using the less-than operator < when performing a search. Since you're storing const char*'s as keys, this means that the lookups will compare the pointers themselves rather than the strings they point to, so if you don't pass in the exact pointer used to insert into the map, the lookup won't find anything.

I think the easiest fix here is to use std::strings as your keys, since the < operator on std::string actually compares the underlying text. That should fix your problem pretty quickly.

like image 140
templatetypedef Avatar answered Dec 27 '22 16:12

templatetypedef