首页 > 解决方案 > C++ unordered_map 奇怪的行为

问题描述

我正在解决 leetcode 问题(总持续时间可被 60 整除的歌曲对),下面的解决方案使用地图,当我将其更改为 unordered_map 并打印循环内的元素时;元素的数量远远多于输入

class Solution {
public:
    int numPairsDivisibleBy60(vector<int>& time) {
        map<int, int> mod_d;
        
        for(auto el : time) {
            if(mod_d.count(el % 60) == 0) {
                mod_d[el % 60] = 1;
            }else mod_d[el % 60]++;
        }
        
        int ans = 0, i = 1;
        //cout << "Size: " << mod_d.size() << "\n";
        for(auto el : mod_d) {
            int f = el.first, s = el.second;
            cout << f << " " << 60 - f << "\n";
            ans += mod_d[(60 - f) % 60] * (((60 - f) % 60) == f ? s - 1 : s);
        }
        
        return ans / 2;
    }
};

样本输入测试:[15、63、451、213、37、209、343、319]

输出如下:

3 57
15 45
19 41
29 31
31 29
33 27
37 23
41 19
43 17
45 15
57 3

循环内打印的元素数量应该只有 8 个,但是使用 unordered_map,元素数量要多得多。

运行不佳的代码如下:

class Solution {
public:
    int numPairsDivisibleBy60(vector<int>& time) {
        unordered_map<int, int> mod_d;
        
        for(auto el : time) {
            if(mod_d.count(el % 60) == 0) {
                mod_d[el % 60] = 1;
            }else mod_d[el % 60]++;
        }
        
        int ans = 0, i = 1;
        //cout << "Size: " << mod_d.size() << "\n";
        for(auto el : mod_d) {
            int f = el.first, s = el.second;
            cout << f << " " << 60 - f << "\n";
            ans += mod_d[(60 - f) % 60] * (((60 - f) % 60) == f ? s - 1 : s);
        }
        
        return ans / 2;
    }
};

唯一的区别是使用 ofunordered_map而不是 amap

它错误地将元素打印为:

19 41
43 17
37 23
33 27
31 29
29 31
3 57
41 19
15 45
41 19
3 57
29 31
31 29
57 3
33 27
37 23
43 17
17 43
19 41
23 37
27 33

任何人都知道为什么会发生这种奇怪的行为?

标签: c++

解决方案


好的,我现在明白了,非常感谢大家的帮助。根据显示访问地图的不同方式的此链接,我看到[]如果元素不在地图中,则使用运算符会创建元素,这是我的错误。当我应该使用 std::map::at 来检索地图元素时

使固定

首先检查元素是否存在并at()用于访问它

class Solution {
public:
    int numPairsDivisibleBy60(vector<int>& time) {
        unordered_map<int, int> mod_d;

        for(auto el : time) {
            if(mod_d.count(el % 60) == 0) {
                mod_d[el % 60] = 1;
            }else mod_d[el % 60]++;
        }

        int ans = 0, i = 1;
        cout << "Size: " << mod_d.size() << "\n";
        for(auto el : mod_d) {
            int f = el.first, s = el.second;
            cout << f << " " << i++ << "\n";
            if(mod_d.count((60 - f) % 60) > 0) ans += mod_d.at((60 - f) % 60) * (((60 - f) % 60) == f ? s - 1 : s);
        }

        return ans / 2;
    }
};

推荐阅读