Search code examples
c++data-structuresc++14std

Map of <int, bool> in C++ defaults to false


I want to insert custom values to my map, which is happening in the first part of the code but not in the second snippet. My code is below:

// First part of the code

unordered_map<int, int> hashmap;

for(int i=0; i<arr.size(); i++)
{
    if(hashmap.find(arr[i]) != hashmap.end())
        hashmap[arr[i]] += 1;
    hashmap.insert(make_pair(arr[i], 1));
}

// Second part of the code

unordered_map<int, bool> hash2;
    
for(auto it=hashmap.begin(); it != hashmap.end(); ++it)
{
    if(hash2[it->second] == true)
        return false;
    hash2.insert(make_pair(it->second, true));
}
return true;

When I try to create a custom map (key-value pair) and set the 'value' to 1 it is working but when I try to create a custom map in the second part of the code it defaults to false.

Can anyone help me debug this issue?


Solution

  • Let's look at the second part:

    unordered_map<int, bool> hash2;
    
    for(auto it=hashmap.begin(); it != hashmap.end(); ++it)
    {
        if(hash2[it->second] == true)                    // 1, 2
            return false;
        hash2.insert(make_pair(it->second, true));       // 3
    }
    return true;                                         // 4
    
    1. hash2[it->second] will insert a bool{} (false) since the Key doesn't exist in the map the first time the value of it->second is used in this lookup. If the same value is used to do another lookup later in the loop, it'll return a reference to the Value stored for the Key (and the Value will be false until changed).
    2. hash2[it->second] returns a reference to the inserted bool and compares == it with true. Since the bool stored in 1. is false, this comparison will always be false, so it will never return false;
    3. Here it tries to insert a pair with the same Key as used above, but with the mapped Value true. This insertion always fails since the Key already exists in the map.
    4. The loop continues until its finished and then the function returns true.