[英]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
}
};
Here is my code.这是我的代码。
I get the error map/set iterator not dereferencable
in the function setMyMap
in the class C
.我在类
C
的函数setMyMap
中得到错误map/set iterator not dereferencable
setMyMap
map/set iterator not dereferencable
。
I get this error because myMap.find("a") == myMap.end()
is true
.我收到此错误是因为
myMap.find("a") == myMap.end()
为true
。
But I don't know why.但我不知道为什么。 To my surprise, I just print this map in the same function and I can see all of the
first
of this map.令我惊讶的是,我只是在同一个函数中打印了这张地图,我可以看到这张地图的
first
。 Here I can see a
.在这里我可以看到
a
. I really don't know why I try to find the same first
but failed.我真的不知道为什么我试图找到相同的
first
,但失败了。 a
is definitely in the map. a
肯定在地图上。 Otherwise I can't print it with that for
.否则我不能用那个
for
打印它。
A map with const char *
as they key does NOT compare the strings, only the pointer addresses.带有
const char *
作为键的映射不比较字符串,只比较指针地址。 Two strings "a"
at different addresses will not compare equal.位于不同地址的两个字符串
"a"
不会比较相等。 You must use std::string
or a custom compare function.您必须使用
std::string
或自定义比较函数。 Do not make assumptions about the addresses of string literals.不要对字符串文字的地址做出假设。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.