RJTK RJTK - 1 year ago 60
C++ Question

Why is my use of Operator[] on std::map invalid?

Suppose I have a map with type

std::map<int, Node> G;

Node is as follows

struct Node{
int data;

I want to use operator[] to return a reference to a Node if it is in the map, or create a new one and return a reference if it is not. That is my understanding of what the documentation says:

If k matches the key of an element in the container, the function returns a reference to its mapped value.

If k does not match the key of any element in the container, the function inserts a new element with that key and returns a reference to its mapped value. Notice that this always increases the container size by one, even if no mapped value is assigned to the element (the element is constructed using its default constructor).

However, the following code throws an error (g++ 5, std=gnu++11):

error: cannot convert ‘std::map::mapped_type {aka Node}’ to ‘Node*’ in assignment u_ptr = G[3];

Node* u_ptr;
u_ptr = G[3];

In all the examples I've seen,
appears on the lhs. Is
not allowed on a rhs? If not, why?

Answer Source

std::map<Key, T>::operator[] returns a T& reference.

In this case, T is Node, so G[3] returns a Node& reference, which you are then trying to assign to a Node* pointer. That is why you are getting a compiler error.

So, you can either:

  1. change u_ptr to a reference:

    Node& u_ptr = G[3];
  2. use the & address operator to convert the reference into a pointer:

    Node* u_ptr;
    u_ptr = &G[3];