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

时间:2012-12-04 05:13:16

标签: visual-c++ stl hashmap

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

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

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

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

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 ];
}

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

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)

笏。

1 个答案:

答案 0 :(得分:5)

问题是您已将功能标记为constoperator[]() 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;
}