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

时间:2013-03-27 14:03:50

标签: 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;
    }
};

错误是:

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

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

[edit]即使我删除了所有typedefs并在任何地方使用std::string,问题仍然存在......我是否滥用了地图?

2 个答案:

答案 0 :(得分:15)

std::map::operator[]是非const的,您尝试使用const方法。

您可以使用std::map::find来实现此目的,该const_iterator会返回SegmentTypeContainer::const_iterator iter = segmentTypes_.find(name);

std::map::at

如果你正在使用C ++ 11,你也可以使用result = segmentTypes_.at(name); ,如果在地图中找不到密钥,则会抛出异常:

{{1}}

答案 1 :(得分:11)

std::map::operator[]不是const方法,但是您是通过班级的const方法调用它的。原因是如果密钥不存在,它会添加一个元素。

您可以使用C ++ 11 at()

result = segmentTypes_.at(name); // throws exception if key not present.

或使用std::map::find

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