2017-03-31 145 views
-2

我在尋找mapunordere_map之間的任何差異,現在大多數人都知道這個差異。地圖解決方案給AC和解決方案與unordered_map給WA。爲什麼?

問題:Problem Link

地圖解決方案: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; 
} 

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 

據我所知,只有與mapunordered_map差異該地圖是否包含以分類方式存在的關鍵字,而unordered_map不是。

+0

作爲[MCVE]的一部分,您需要提供輸入以及問題主體中的預期和觀察輸出。請編輯它們,鏈接到外部網站要求我們做更多的工作,並增加鏈接腐爛的風險,使您的問題對未來的讀者無法理解。 – ShadowRanger

+0

我也提供了輸入和期望的輸出。我把鏈接放在了更多的說明中。無論如何,問題有足夠的信息。 –

回答

2

mp[(X-1)]可能需要在地圖中插入新元素(如果密鑰X-1已不存在)。使用std::map,插入新元素不會使任何現有的迭代器失效。使用std::unordered_map,它可能(如果插入恰好觸發重新哈希)。當它確實時,it變得無效,並且隨後的++it表現出未定義的行爲。

+0

由於 現在它的工作如 //簡單的檢查,訪問 之前如果(mp.find(X-1)!= mp.end()){ ANS = MAX(ANS,熔點[(X-1) ] +熔點[(X)]); } –