0
#include <iostream>
#include <map>

using namespace std;
int main()
{
    map<int, int> m;
    for (int i = 0; i < 5; i++)
        m[i]++;

    for (int i = 0; i < 5; i++)
        cout<<m[i];
}

Output:

11111

Now, how come value of m[i] is getting initialized? Shouldn't it translate to m[i]'s value incremented by 1?

Pranit Kothari
  • 9,721
  • 10
  • 61
  • 137

2 Answers2

5

Shouldn't it translate to m[i]'s value incremented by 1?

It is. when you do map[key] if key does not exist it adds it to the map and value initializes the value that is mapped to key. For an int value initialization means zero initialization. So, m[i] is 0, and the the ++ increments it to 1.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
3

If you looks at the docs for std::map::operator[]

Returns a reference to the value that is mapped to a key equivalent to key, performing an insertion if such key does not already exist.

So basically m[i] will perform an insertion if that key does not already exist, then the increment will occur with a reference to the newly inserted value.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218