我在 map C++ 中得到了意想不到的 count() 行为

问题描述

<?PHP
include('simple_html_dom.PHP');
$html = str_replace(',','.',$html);
$html = file_get_html('https://www.funda.nl/beoordelingenwidget/live/16186/3/3%3d33%3b6%3d62/aankoop/');
echo $html->find(".user-reviews-averages-number",0);
?>

输出: 0 1 0

至少对我来说毫无意义,为什么要这样:

#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;
}

将 count 的值增加 1,同时 int a = nums_map[0]; = 0。

解决方法

因为 std::map::operator[] 的工作方式有点奇怪。来自the documentation on 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;
}