[英]c++ map/set iterator not dereferencable --- map<const char *, string>
class A
{
public:
map<string, string> strs; // it's initialized in a function
map<const char *, string> myMap;
virtual void setMyMap()
{
myMap.insert({str.begin()->first.c_str(), "aaa"});
}
};
class B : public class A
{};
class C : public class B
{
virtual void setMyMap()
{
B::setMyMap();
for (auto it = myMap.begin(); it != myMap.end(); ++it)
{
cout << it->first << std::endl; // "a"
}
cout<<(myMap.find("a") == myMap.end()); // 1
myMap.find("a")->first; // get the error
}
};
这是我的代码。
我在类C
的函数setMyMap
中得到错误map/set iterator not dereferencable
setMyMap
map/set iterator not dereferencable
。
我收到此错误是因为myMap.find("a") == myMap.end()
为true
。
但我不知道为什么。 令我惊讶的是,我只是在同一个函数中打印了这张地图,我可以看到这张地图的first
。 在这里我可以看到a
. 我真的不知道为什么我试图找到相同的first
,但失败了。 a
肯定在地图上。 否则我不能用那个for
打印它。
带有const char *
作为键的映射不比较字符串,只比较指针地址。 位于不同地址的两个字符串"a"
不会比较相等。 您必须使用std::string
或自定义比较函数。 不要对字符串文字的地址做出假设。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.