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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With