Search code examples
c++stdmapstd-pair

how does the compiler write values to the second value of the pair in this construct?


map<int,int> a;
pair<std::map<int,int>::iterator ,bool> f;
f=(a.insert({0,0}));
cout<<f.second;

why is it outputting 1?

it always outputs 1 for any values in the pair


Solution

  • It's because the bool f.second tells you if insert inserted the pair<int,int> into the map. 1 means that it did insert it.

    bools are normally printed as either 0 (false) or 1 (true). You can use the I/O manipulator std::boolalpha to make it print true or false instead.

    it always outputs 1 for any values in the pair

    No. If you try to insert a pair with a Key value that already exists in the map<int,int> it will return a pair<std::map<int,int>::iterator ,bool> where the bool is false and the iterator will point at the existing element in the map<int,int>.