问题
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.
回答1:
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.
回答2:
You can have several options to fix that:
1) You can use std::string instead of const char *
template<
class Key,
class T,
class Compare = std::less<Key>,
class Allocator = std::allocator<std::pair<const Key, T> >
> class map;
2) Map declaration can be seen above. Third template parameter is compare functor. You can pass your map a custom functor to implement the right behavior.
3) std::less uses operator< . You can write operator< for const char * .
来源:https://stackoverflow.com/questions/35730615/stdmap-find-not-working-in-c