c++ - 我在地图 C++ 中遇到了 count() 的意外行为
问题描述
#include<bits/stdc++.h>
using namespace std;
int main() {
map<int, int> nums_map;
cout << nums_map.count(0) << endl;
int a = nums_map[0];
cout << nums_map.count(0) << endl;
cout << nums_map[0];
return 0;
}
输出:0 1 0
至少对我来说没有意义,为什么这条线:
int a = nums_map[0];
正在将 count 的值增加 1,同时也将nums_map.empty()
= 0。
解决方案
因为std::map::operator[]
工作方式有点奇怪。从文档中std::map::operator[]
:
返回对映射到与 key 等效的键的值的引用,如果这样的键不存在,则执行插入。
因此,如果密钥不存在,它会创建一个新的对。这正是这里发生的事情。
#include <iostream>
#include <map>
int main() {
using namespace std;
map<int, int> nums_map; // nums_map == {}
cout << nums_map.count(0) << endl; // 0, because the map is empty
int a = nums_map[0]; /* a new key/value pair of {0, 0} is
created and a is set to nums_map[0],
which is 0 */
cout << nums_map.count(0) << endl; // Since there is one key 0 now, this shows 1
cout << nums_map[0]; // As shown previously, nums_map[0] is 0
return 0;
}
推荐阅读
- xml - 无法使用 Go 获取 XML 属性
- git - git@github.com:权限被拒绝(公钥)
- python - 我的 pyecharts 没有名为“pyecharts.engine”的模块
- flutter - Flutter:将图标对齐到中间——底部导航栏
- visual-studio-code - 斜体适合正则表达式 VSCode 的行
- python-3.x - 如何在pivot_table之后选择A列大于B列的行
- ios - navigationController?.popViewController(animated: true) 不会取消初始化视图控制器
- python - 如何将扩展名为 .png 的图形从一个文件夹移动或复制到另一个文件夹?
- angular - 使用异步验证和 Ngrx 存储的反应式表单验证
- react-native - Redux-Persist - 如何有条件地将商店持久化为反应原生