std :: map查找不适用于C ++ [英] std::map find not working in C++

查看:52
本文介绍了std :: map查找不适用于C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下几行创建了一个哈希映射和一个迭代器:

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());

然后,每当我尝试使用下面的几行来搜索此映射或螺母中是否存在特定字符串的条目时,它始终会输入 IF 块,换句话说,它不会在其中找到任何条目这张地图.

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());

注意:此处 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
}

此外,这是在C ++中创建和使用std :: map的正确方法吗?如果没有,请提出一个建议.

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

此外,我还没有使用关键字 new 来创建std :: map对象.

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

推荐答案

std :: map 中,使用小于 operator< 的键对键进行比较.执行搜索时.由于您将 const char * 作为键存储,这意味着查找将比较指针本身而不是它们指向的字符串,因此,如果您不传递所使用的确切指针插入地图后,查找将不会找到任何内容.

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.

我认为最简单的解决方法是使用 std :: strings 作为键,因为 std :: string < 运算符>实际上比较基础文本.那应该可以很快解决您的问题.

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.

这篇关于std :: map查找不适用于C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆