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
。
我得到这个错误是因为myMap.find("a") == myMap.end()
是true
。
但我不知道为什么。令我惊讶的是,我只是在相同的函数中打印这张地图,我可以看到这张地图的所有first
。这里我可以看到a
。我真的不知道为什么我试图找到相同的first
,但失败了。a
肯定在地图上。否则我不能用for
打印它
以const char *
为键的映射不比较字符串,只比较指针地址。两个位于不同地址的字符串"a"
比较起来不相等。必须使用std::string
或自定义比较函数。不要假设字符串字面值的地址