tags:

views:

92

answers:

3

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]);
+1  A: 

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.

Charles Bailey
+5  A: 

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.

R Samuel Klatchko
A: 

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.

Remy Lebeau - TeamB