gpt4 book ai didi

c++ - unordered_map 索引错误

转载 作者:行者123 更新时间:2023-11-30 03:13:23 25 4
gpt4 key购买 nike

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

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

最佳答案

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

关于c++ - unordered_map 索引错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58729240/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com