【问题标题】:Solution with map gave AC and Solution with unordered_map gave WA. why?带有地图的解决方案给出了 AC,带有 unordered_map 的解决方案给出了 WA。为什么?
【发布时间】:2017-03-31 12:58:39
【问题描述】:

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

问题: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 的唯一区别是 map 包含排序方式的键,而 unordered_map 不包含。

【问题讨论】:

  • 作为minimal reproducible example 的一部分,您需要在问题正文中提供输入以及预期和观察到的输出。请编辑它们,链接到外部网站要求我们做更多的工作,并增加链接失效的风险,使未来的读者无法理解您的问题。
  • 我也提供了输入和预期输出。我放了链接以获得更多说明。无论如何问题都有足够的信息。

标签: c++ c++11 dictionary unordered-map keymaps


【解决方案1】:

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

【讨论】:

  • 谢谢 现在它可以作为 // 简单检查,在访问之前 if( mp.find(X-1)!=mp.end()){ ans = max(ans,mp[(X- 1)]+mp[(X)]); }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-26
  • 1970-01-01
  • 1970-01-01
  • 2015-04-22
  • 2022-10-31
  • 1970-01-01
相关资源
最近更新 更多