【问题标题】:problem in traversing through unordered_map cpp遍历unordered_map cpp的问题
【发布时间】:2023-04-04 05:40:02
【问题描述】:

我遍历unordered_map时只有一半的测试用例通过,但是当我使用vector时它们都通过了,我的代码有什么错误吗?

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n;  cin>>n;
    unordered_map<int,int> mp;
    vector<int> v;  v.reserve(n);
    while(n--)
    {
        int x,y;  cin>>x>>y;
        int h=y+x;
        if(mp[h]==0){ v.push_back(h); }
        mp[h]++;
    }
    int s; cin>>s;  int sa=0;
    for(auto i:mp)
    {
        int j=i.first+s;
        long long u=mp[j]*(i.second);
        sa=sa+u;
    }
    cout<<sa;
}

【问题讨论】:

  • 你想做什么?顺便说一句,这看起来像 UB,因为默认插入了 int if(mp[h]==0)
  • @pptaszni 是值初始化的,这里没有UB。
  • 测试用例在测试什么?你的代码期望做什么?您的代码中有什么意外?

标签: c++ unordered-map


【解决方案1】:

在这个循环中:

for(auto i:mp)
{
    int j=i.first+s;
    long long u=mp[j]*(i.second);
    sa=sa+u;
}

当您执行mp[j] 时,您可能会修改mp,如果j 不是unordered_map 中的键。修改您在 range-for 循环中迭代的范围会调用未定义的行为。

您可以使用find 检查密钥j 是否存在并在这种情况下执行其他操作(但不要修改unordered_map)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-18
    • 2011-11-19
    • 2011-09-06
    • 1970-01-01
    • 2019-02-26
    相关资源
    最近更新 更多