2

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;
}
manoj
  • 29
  • 2
  • 1
    See https://stackoverflow.com/q/695645/1896169 . It also appears that `mp[0]` is evaluated before `mp.size()`, then the assignment operator is evaluated. – Justin Jul 05 '19 at 15:51
  • That duplicate link is actually looking at exactly the same behavior with a `map` and `mp[10] = mp.size();` – Justin Jul 05 '19 at 15:57
  • Which compiler are you using? Both [gcc](https://wandbox.org/permlink/ZAXnMgwPXi6gPL6s) and [clang](https://wandbox.org/permlink/m4JU4wzJnsPbHMDK) say `0`. – songyuanyao Jul 05 '19 at 16:09
  • i am using gcc compiler – manoj Jul 05 '19 at 16:13
  • @songyuanyao That's because the standard you are using is >C++17. In a conforming C++17 implementation, this is well behaved and will set `mp[0]` to `0`. Compiler versions which support C++17 may choose to support this behavior for all standard versions. – Justin Jul 05 '19 at 18:03
  • 1
    @Justin Then the answer should be *Before C++17 the behavior is unspecified, since C++17 the result is 0* ? – songyuanyao Jul 06 '19 at 03:23
  • 1
    @songyuanyao Yes – Justin Jul 06 '19 at 13:59

2 Answers2

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.

Steven Sudit
  • 18,659
  • 1
  • 44
  • 49
0

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;
Steven Sudit
  • 18,659
  • 1
  • 44
  • 49