C++ 映射/设置迭代器不可取消引用 --- map<const char *,字符串>


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或自定义比较函数。不要假设字符串字面值的地址

相关内容

最新更新