首页 > 解决方案 > unordered_map 索引错误

问题描述

我无法访问 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”。我很困惑,不知道机制是什么。有人可以帮我吗?先感谢您。

标签: c++hashreferencehashtable

解决方案


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


推荐阅读