c++ - 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”。我很困惑,不知道机制是什么。有人可以帮我吗?先感谢您。
解决方案
该程序具有未定义的行为,因为在添加等于 5 的新元素之后,迭代器无效mp[it.first+k]
。it.first
推荐阅读
- python-3.x - Python3 中的 NLP - 计算大字符串中特定术语的出现次数
- visual-studio-code - vscode 不会自动将当前单词放入 find
- css - 在鼠标关闭事件上更改动画原点
- javascript - 通过连续添加字母直到完成整个单词,创建一个接收单词并拼写出来的函数
- helix - 如何使用发明者 api 和 c# 或 vb.net 创建螺旋曲线
- java - 如何定义传递给方法的流利 lambda 的顺序
- python - 如何获得 df 的另一个条件?
- python - 如何在不使用熊猫的情况下编写此代码?
- sql-server - 如何使用 sql 语句将数据从 SQL Server 导出到 CSV 文件
- javascript - Thingsboard - 绘制带有未来时间戳的遥测数据