代码之家  ›  专栏  ›  技术社区  ›  Joe Bane

C++ const STD::map引用无法编译

  •  14
  • Joe Bane  · 技术社区  · 17 年前

    std::map

    错误:中的运算符[]不匹配 地图[名称]

    void func(const char ch, std::string &str, const std::map<std::string, std::string> &map);
    

    而且,我应该提到,当我移除 const 前面的关键字 .

    如果我得到了正确的指示,[]操作符实际上会在没有找到密钥的情况下向映射中插入一个新的对,这当然可以解释为什么会发生这种情况,但我无法想象这会是一种可接受的行为。

    如果有更好的方法,比如使用 发现 常数 不匹配的迭代器错误。

    5 回复  |  直到 8 年前
        1
  •  26
  •   Johannes Schaub - litb    17 年前

    是的,你不能用 operator[] . 使用 find ,但请注意它会返回 const_iterator 而不是 iterator :

    std::map<std::string, std::string>::const_iterator it;
    it = map.find(name);
    if(it != map.end()) {
        std::string const& data = it->second;
        // ...
    }
    

    就像指针一样。你不能分配 int const* 到 int* . 同样,您也不能指定 常量迭代器 到 .

        2
  •  7
  •   Benoît photo_tom    17 年前

    当您使用运算符[]时,std::map将查找具有给定键的项。如果找不到,它就会创建它。因此,const存在问题。

    使用“查找”方法,您会没事的。

    您能否发布有关如何使用find()的代码? 正确的方法是:

    if( map.find(name) != map.end() )
    {
       //...
    }
    
        3
  •  4
  •   Rohit Shrinath    12 年前

    std::map::at 应该对你有用。

    原因 std::map::operator[] 不起作用的是,如果您要查找的键在映射中不存在,它将使用提供的键插入新元素并返回对它的引用(有关详细信息,请参阅链接)。这在const std::map上是不可能的。

    但是,如果密钥不存在,“at”方法将抛出异常。也就是说,在尝试使用“at”方法访问元素之前,最好使用std::map::find方法检查密钥是否存在。

        4
  •  2
  •   Fred Larson    17 年前

    可能是因为std::map中没有常量运算符[]。运算符[]将添加您要查找的元素(如果找不到)。因此,如果要在不添加任何内容的情况下进行搜索,请使用find()方法。

        5
  •  2
  •   Dan Breslau    17 年前

    find()有两个重载:

          iterator find ( const key_type& x );
    const_iterator find ( const key_type& x ) const;
    

    我的 猜测 您之所以会出现此错误,是因为您正在执行类似于将非常量迭代器(位于左侧)分配给 find() 拜访 const 地图:

    iterator<...> myIter /* non-const */ = myConstMap.find(...)
    

    这将导致一个错误,尽管可能不是您看到的错误。