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

青春壹個敷衍的年華 提交于 2021-02-07 19:26:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!