带地图的解决方案给了空调,unordered_map的解决方案给了WA.为什么



我正在寻找现在大多数人都知道的mapunordere_map之间的任何区别。

问题 : 问题链接

带地图的解决方案:接受的解决方案

#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;
}

unordered_map的解决方案:WA解决方案

#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

据我所知,与mapunordered_map的唯一区别是地图以排序方式包含键,而unordered_map则不包含。

mp[(X-1)]可能需要在映射中插入一个新元素(如果键X-1尚不存在(。使用 std::map ,插入新元素不会使任何现有的迭代器失效。使用 std::unordered_map ,它可能(如果插入碰巧触发重新散列(。当它出现时,it将变为无效,后续++it表现出未定义的行为。

相关内容

最新更新