Question

Is the following code OK?

class A
{
  public:
    A();
    void foo();
};

map<int,A> m;
m[0].foo();

Or do I have to do the following:

map<int,A> m;
m[0] = A();
m[0].foo();

And also, can I do this:

map<int,A> m;
A a = m[5];

And how about access by reference:

void foo(A & a);
map<int,A> m;
foo(m[5]);
Was it helpful?

Solution

map::operator [] will create a new value on the fly if it doesn't already exist. So all of your code examples will work.

That said, this example:

 map<int,A> m;
 m[0] = A(); // redundant
 m[0].foo();

is overkill as the second line is redundant.

OTHER TIPS

Yes, they are all valid usages. operator[] returns a reference to the value half of the key-value pair that either already existed or was inserted by the operator[] itself in the call.

When you use the '[]' operator of a std::map, a new object will be default-constructed automatically if no item with the specified ID exists yet.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top