c++c++11dictionaryunordered-mapkeymaps

Solution with map gave AC and Solution with unordered_map gave WA. why?


I am looking for any difference between map and unordere_map which is now known by most of people.

The problem : Problem Link

the solution with map: Accepted Solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    int N;
    cin >> N;
    map<int,int> mp;
    map<int,int> ::iterator it;
    int ans = 0;
    for(int i=0;i<N;i++){
        int X;
        cin >> X;
        mp[X]++;
    }    
    for(it=mp.begin();it!=mp.end();++it){
        int X = it->first;   
        //cout<<it->first<<" "<<it->second<<endl;
        ans = max(ans,mp[(X-1)]+mp[(X)]);
    }
    cout<<ans<<endl; 
    return 0;
}

The solution with unordered_map: WA Solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    int N;
    cin >> N;
    unordered_map<int,int> mp;
    unordered_map<int,int> ::iterator it;
    int ans = 0;
    for(int i=0;i<N;i++){
        int X;
        cin >> X;
        mp[X]++;
    }     
    for(it=mp.begin();it!=mp.end();++it){
        int X = it->first;   
        //cout<<it->first<<" "<<it->second<<endl;
        ans = max(ans,mp[(X-1)]+mp[(X)]);
    }
    cout<<ans<<endl; 
    return 0;
}


Input :
       98
       7 12 13 19 17 7 3 18 9 18 13 12 3 13 7 9 18 9 18 9 13 18 13 13 18 18 17 17 13 3 12 13 19 17 19 12 18 13 7 3 3 12 7 13 7 3 17 9 13 13 13 12 18 18 9 7 19 17 13 18 19 9 18 18 18 19 17 7 12 3 13 19 12 3 9 17 13 19 12 18 13 18 18 18 17 13 3 18 19 7 12 9 18 3 13 13 9 7
Output : 10
Expected Output : 30

As far as I know that only difference with map and unordered_map is that map contain key in sorted fashion while unordered_map not.


Solution

  • mp[(X-1)] may need to insert a new element into the map (if the key X-1 wasn't present already). With std::map, inserting a new element doesn't invalidate any existing iterators. With std::unordered_map, it may (if insertion happens to trigger rehashing). When it does, it becomes invalid and the subsequent ++it exhibits undefined behavior.