If initially size of map is 0, then why mp[0] is equal to 1? Why output is 1 here?
#include<iostream>
#include<map>
using namespace std;
int main()
{
map<int,int> mp;
mp[0]=mp.size();
cout<<mp[0];
return 0;
}
If initially size of map is 0, then why mp[0] is equal to 1? Why output is 1 here?
#include<iostream>
#include<map>
using namespace std;
int main()
{
map<int,int> mp;
mp[0]=mp.size();
cout<<mp[0];
return 0;
}
To understand it let’s break down this line:
mp[0] = mp.size();
Firstly,
mp.operator[](0)
gets called. What it does is it checks whether there currently exists an element at index 0. It doesn’t, so it creates this element and immediately returns a reference to it. Than this element is assigned the value of
mp.size()
At this time, this is already 1 because of the just created element.
Justin's comment is pretty much the answer, but I'll flesh it out.
When you use operator[]
on a map, with a new key, it inserts an element. In this case, it inserts the element before it takes the size of the map. You can get the desired behavior by taking the size and holding it in a temporary. Something like...
size_t size = mp.size();
mp[0] = size;