首页 > 解决方案 > 我在地图 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。

标签: c++c++11c++17

解决方案


因为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;
}

推荐阅读