【问题标题】:Wrong indexing with unordered_mapunordered_map 索引错误
【发布时间】:2020-03-02 21:12:12
【问题描述】:

我无法访问 unordered_map 的键。以下是我的代码:

#include <iostream>
#include <unordered_map>
#include <vector>

using namespace std;

int main() {
    vector<int> nums = {1,2,3,4,5};
    int k = 2;
    unordered_map<int,int> mp;
    for(auto num : nums)
        mp[num]++;
    for(auto it : mp)
        cout << it.first;
    cout << endl;
    for(auto it : mp)
        cout << mp[it.first+k];
    return 0;
}

我希望输出是

54321

00111

因为 "7","6","5","4","3" 的键值是 "0","0","1","1","1"。但输出是

54321

0000

注意这里只有四个“0”。我很困惑,不知道机制是什么。有人可以帮我吗?提前谢谢你。

【问题讨论】:

  • 您在迭代地图时正在修改地图,这是未定义的行为
  • 你有 UB,当迭代 mp 元素时,你通过调用 [] 创建一个新的,所以你的循环被打破了 - end mp 的迭代器被改变了。

标签: c++ hash reference hashtable


【解决方案1】:

程序具有未定义的行为,因为在此之后添加新元素 mp[it.first+k] for it.first 等于 5 迭代器无效。

【讨论】:

  • 感谢您的回答!还有一个问题,如果我执行“vector nums = {1,2,3,4,5}; for(auto num : nums) nums.push_back(num)”之类的事情会发生什么?我希望它是无限循环,但它返回“1234511-2144292696132”。
  • @YizeWang 再次存在未定义的行为。例如,当推入新元素时,向量可以重新分配内存。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-10
  • 1970-01-01
相关资源
最近更新 更多