【问题标题】:Why will my std::map not accept its key as an index via its subscript operator?为什么我的 std::map 不通过其下标运算符接受其键作为索引?
【发布时间】:2012-12-04 05:13:15
【问题描述】:

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

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)

笏。

【问题讨论】:

  • 你能确切地说明m_Mapm_Map2是如何声明的吗?

标签: visual-c++ stl hashmap


【解决方案1】:

问题是您在std::map 上将函数标记为constoperator[]() 修改了映射(如果键不在映射中,则添加具有默认值的元素)。

你可以在使用指针时避开这个问题,因为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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-21
    • 2013-07-21
    • 1970-01-01
    • 1970-01-01
    • 2010-12-23
    • 1970-01-01
    • 2012-01-12
    • 1970-01-01
    相关资源
    最近更新 更多