2013-03-27 35 views
6

这无法在GCC编译器4.1.2/RedHat的5:错误:不对应的 '操作[]' 在...... <near match>

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

为什么?地图相当简单。我想这与typedefs有关,但是出了什么问题?

即使我删除所有typedefs并使用std::string无处不在,问题仍然存在......我滥用地图吗?

回答

15

std::map::operator[]是非常量,你试图从const方法中使用它。如果该键没有找到

SegmentTypeContainer::const_iterator iter = segmentTypes_.find(name); 

如果您使用C++ 11,你也可以使用std::map::at,这将抛出一个异常:

你可以做到这一点使用std::map::find,它返回一个const_iterator在地图:

result = segmentTypes_.at(name); 
+0

或者'at'在C++中11。 +1 – 2013-03-27 14:07:52

+0

@LuchianGrigore我很确定'at'在C++之前就存在了11 – Saage 2013-03-27 14:09:27

+0

@Saage只是作为一个扩展。现在它是标准的。 – juanchopanza 2013-03-27 14:09:52

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; 
} 
相关问题