微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决我在 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;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。