错误:在... <near match>中与'operator []'不匹配

Off*_*rmo 6 c++

这无法在gcc 4.1.2/RedHat 5中编译:

#include <string>
#include <vector>
#include <map>

class Toto {
public:
    typedef std::string SegmentName;
};

class Titi {
public:
    typedef Toto::SegmentName SegmentName; // import this type in our name space
    typedef std::vector<SegmentName> SegmentNameList;
    SegmentNameList segmentNames_;
    typedef std::map<SegmentName, int> SegmentTypeContainer;
    SegmentTypeContainer segmentTypes_;

    int getNthSegmentType(unsigned int i) const {
        int result = -1;

       if(i < segmentNames_.size())
       {
           SegmentName name = segmentNames_[i];
           result = segmentTypes_[ name ];
       }
       return result;
    }
};
Run Code Online (Sandbox Code Playgroud)

错误是:

error: no match for 'operator[]' in '(...)segmentTypes_[name]'
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_map.h:340:
note: candidates are: _Tp& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const _Key&)
[with _Key = std::basic_string<char, std::char_traits<char>, std::allocator<char> >, _Tp = int, _Compare = std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, _Alloc = std::allocator<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, int> >]
Run Code Online (Sandbox Code Playgroud)

为什么?地图相当简单.我想这与typedef有关,但有什么不对?

[编辑]即使我删除所有typedefsstd::string在任何地方使用,问题仍然存在......我是否滥用地图?

mfo*_*ini 16

std::map::operator[]是非const的,你试图从一个const方法中使用它.

你可以实现这个std::map::find,它返回一个const_iterator:

SegmentTypeContainer::const_iterator iter = segmentTypes_.find(name);
Run Code Online (Sandbox Code Playgroud)

如果您正在使用C++ 11,您也可以使用std::map::at,如果在地图中找不到密钥,则会抛出异常:

result = segmentTypes_.at(name);
Run Code Online (Sandbox Code Playgroud)


jua*_*nza 11

std::map::operator[]不是const方法,而是从const类的方法调用它.这样做的原因是,如果密钥不存在,它会添加一个元素.

你可以使用C++ 11 at():

result = segmentTypes_.at(name); // throws exception if key not present.
Run Code Online (Sandbox Code Playgroud)

或使用std::map::find.

SegmentTypeContainer::const_iterator it = segmentTypes_.find(name);
if (it != segmentTypes_.end())
{
  // OK, element with key name is present
  result = it->second;
}
Run Code Online (Sandbox Code Playgroud)