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

q251416140 回答:unordered_map的索引编制错误

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

本文链接:https://www.f2er.com/3152603.html

大家都在问