std::map<int,bool> wrong result of insert?

Viewed 119
#include <iostream>
#include <map>

using namespace std;

int main()
{
    std::map<int, bool> set;
    
    cout << (int)set.insert({ 5,false }).second << endl;
    return 0;
}

I don't know why the result is 1 instead of 0, while second is false.

1 Answers

std::map::insert's return value is an std::pair<iterator, bool> where the bool denotes whether insertion took place. cout << (int)set.insert({ 5,false }).second << endl; will only print whether insertion successfully took place.

To do what you want, you'll want to use the first value in the returned std::pair which is an iterator and then use that to check the value of the new key/value pair that you inserted:

#include <iostream>
#include <map>

int main()
{
    std::map<int, bool> set;
    std::cout << set.insert({5, false}).first->second << '\n';
    return 0;
}
Related