Error: no match for 'operator []' in ... <near match>

This is not compiled in 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:

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

Why? The map is pretty simple. I assume this is due to typedefs, but what is wrong?

[edit] Even if I delete all typedefs and use std::string everywhere, the problem persists ... Am I using maps incorrectly?

+6
source share
2 answers

std::map::operator[] not const and you are trying to use it from the const method.

You can achieve this using std::map::find , which returns const_iterator :

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

If you use C ++ 11, you can also use std::map::at , which throws an exception if the key is not found on the map:

 result = segmentTypes_.at(name); 
+15
source

std::map::operator[] not const , but you are calling it from the const method of your class. The reason for this is that it adds an item if the key is missing.

You can use C ++ 11 at() :

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

or use std::map::find .

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

All Articles