为什么我的std :: map不能通过其下标运算符接受其键作为索引?

zeb*_*und 1 stl hashmap visual-c++

我的代码最初看起来像这样:

int SomeObject::operator[]( const string& key ) const
{
    return ( *m_Map )[ key ];
}

int SomeObject::operator()( const string& key ) const
{
    return ( *m_Map2 )[ key ];
}
Run Code Online (Sandbox Code Playgroud)

这两张地图都有以下签名:

std::map< std::string, int >

然后我读了一些关于STL容器真的不需要显式堆分配(即std::map< ... >* map = new std::map< ... >),这就是我正在做的事情.

只要我将映射更改为堆栈分配并删除指针取消引用,它就像这样:

int SomeObject::operator[]( const string& key ) const
{
    return m_Map[ key ];
}

int SomeObject::operator()( const string& key ) const
{
    return m_Map2[ key ];
}
Run Code Online (Sandbox Code Playgroud)

编译器抱怨以下错误(对于两个映射):

Error   1   error C2678: binary '[' : no operator found which takes a left-hand operand of type 'const std::map<_Kty,_Ty>' (or there is no acceptable conversion)
Run Code Online (Sandbox Code Playgroud)

笏.

Mic*_*urr 5

问题是你已经将函数标记为on constoperator[]()on std::map修改了地图(如果键不在地图中,则添加一个默认值的元素).

你可以在使用指针时逃避这一点,因为const它只应用于成员指针,而不是指针引用的对象.

像下面这样的东西应该解决这个const问题:

int SomeObject::operator[]( const string& key ) const
{
    std::map<string,int>::const_iterator it(m_Map.find(key));

    if (it == m_Map.end()) {
        throw /* something */;
    }

    return it->second;
}
Run Code Online (Sandbox Code Playgroud)