Home > Software engineering >  What is the difference between if(map[arr[i]]) and if (map.find(arr[i]) != map.end()) ? When looking
What is the difference between if(map[arr[i]]) and if (map.find(arr[i]) != map.end()) ? When looking

Time:02-04

The task is to find common substring. The solution worked when I changed my if statement. So what is the difference between ->>>>> if(map.find(...) != map.end()) and if(map[a..[..]])

Correct code:

 unordered_map<char, int> map;   

for(int i = 0; i < s1.size(); i  )        
    map[s1[i]]  ;   
             *emphasized text*
  for(int i = 0; i < s2.size(); i  )        
    if(map[s2[i]])            
      return "YES"; 
       
  return "NO";
}

CodePudding user response:

The line:

 if(map.find(X) != map.end())

Checks to see if X exists in the map and will return true if it is there (thus entering your test condition).

The line:

if(map[<X>])

If X exists in the map then it will return the associated value. If X does not exist in the map then it will be inserted and a default value will be constructed and will be the result of the operator[]. It is the value returned by operator[] that is then converted to a bool to decide if the branch is taken.

The difference between the two:

  • if(map.find(X) != map.end())
    Does not change map.
    Branch if the item <X> exists in the map.
  • if(map[<X>])
    Mutates the map if the key 'X' does not exist.
    Branch depends on the value associated with the key X.
    Note: A default constructed value does not always evaluate to false it will depend on the type. Though in your case unordered_map<char, int> map; the value type is int and the default (or default value constructed object in the map) for an integer is 0 and thus converts to false.

CodePudding user response:

One difference is that if(map[s2[i]]) will insert a 0 in the map for that key. A side effect is that the subsequent if(map.find(...) != map.end()) will find that 0 value.

  •  Tags:  
  • Related