The following code says that passing the map as const into the operator[] method discards qualifiers:
#include <iostream> #include <map> #include <string> using namespace std; class MapWrapper { public: const int &get_value(const int &key) const { return _map[key]; } private: map<int, int> _map; }; int main() { MapWrapper mw; cout << mw.get_value(42) << endl; return 0; }
Is this because of the possible allocation that occurs on the map access? Can no functions with map accesses be declared const?
MapWrapper.cpp:10: error: passing const std::map<int, int, std::less<int>, std::allocator<std::pair<const int, int> > > as this argument of _Tp& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const _Key&) [with _Key = int, _Tp = int, _Compare = std::less<int>, _Alloc = std::allocator<std::pair<const int, int> >] discards qualifiers
std::map‘soperator []is not declared asconst, and cannot be due to its behavior:As a result, your function cannot be declared
const, and use the map’soperator[].std::map‘sfind()function allows you to look up a key without modifying the map.find()returns aniterator, orconst_iteratorto anstd::paircontaining both the key (.first) and the value (.second).In C++11, you could also use
at()forstd::map. If element doesn’t exist the function throws astd::out_of_rangeexception, in contrast tooperator [].