2013-03-27 10 views
6

To nie kompilacji w gcc 4.1.2/RedHat 5:błąd: nie pasuje do 'operator []' w ... <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; 
    } 
}; 

Błąd jest:

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

Dlaczego ? Mapa jest dość prosta. Myślę, że ma to związek z typedefs, ale co jest nie tak?

[edytuj] Nawet jeśli usuniemy wszystkie typedefs i użyję wszędzie std::string, problem będzie nadal występował ... Czy niewłaściwie używam map?

Odpowiedz

15

std::map::operator[] nie jest const i próbujesz go użyć w metodzie const.

Można to osiągnąć stosując std::map::find, która zwraca const_iterator:

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

Jeśli używasz C++ 11, można też użyć std::map::at, który wygeneruje wyjątek, jeśli klucz nie został znaleziony w mapie:

result = segmentTypes_.at(name); 
+0

Lub 'at' w C++ 11. +1 –

+0

@LuchianGrigore Jestem prawie pewny, że 'at' istniał przed C++ 11 – Saage

+0

@Sageage tylko jako rozszerzenie. Teraz jest standardem. – juanchopanza

11

std::map::operator[] nie jest metodą const, ale wzywają go z const metody klasy. Powodem tego jest to, że dodaje element, jeśli klucz nie jest obecny.

Można używać C++ 11 at():

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

lub użyj std::map::find.

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