Mox Mox - 9 months ago 34
C++ Question

C++ accessing map element via pointer object key giving illegal operation error

Ok here is the code snippet that I am having the problem with (class name has been changed due to work reason)

const std::map<A*, std::pair<int, B*> > &aMap = ot->getAMap();
A *a = getAFromSomewhere();
B* b = aMap[a].second; //The line that the compilation error points to.



Error: The operation "
const std::map<A*, std::pair<int, B*>, std::less<A*>, std::allocator<std::pair<A*const, std::pair<int, B*>>>>[A*]
" is illegal.


anyone has any idea why this is so?

Answer Source

The subscript operator for the class std::map is declared like

T& operator[](const key_type& x);
T& operator[](key_type&& x);

As you can see it is declared for non-constant objects of the class because if there is no object in the map with the given key then it is created by the operator.

And your object is constant due to the constant reference

const std::map<A*, std::pair<int, B*> > &aMap = ot->getAMap();
^^^^^

You should use member function at that is declared for constant objects.

const T& at(const key_type& x) const;
                               ^^^^^

If you have an old compiler that does not support C++ 2011 then you can use member function find.