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

C ++更新unordered_map中的值,其中键值对的数据类型为int-unordered_set

如何解决C ++更新unordered_map中的值,其中键值对的数据类型为int-unordered_set

我正在解决DSA问题,并在C ++标准模板库中观察到了一个有点奇怪的行为:

    vector<int> v = {1,7,8,3,12};

    unordered_map<int,unordered_set<int>> ump;

    for (int i=0; i<v.size(); i++) {
        unordered_set<int> us;
        us.insert(56);
        ump.insert(mp(v[i],us));
    }
    
    for (int i=0; i<v.size(); i++) {
        unordered_set<int> us = ump.find(v[i])->second;
        us.insert(67);
    }

    for (auto it = ump.begin(); it != ump.end(); it++) {
        cout << it->first << ": ";
        for (auto ait = it->second.begin(); ait!=it->second.end(); ait++) {
            cout << *ait << ' ';
        }
        cout << '\n';
    }

输出将变为:

12: 56 
3: 56 
8: 56 
7: 56 
1: 56 

但预期输出应为:

12: 67 56 
3: 67 56 
8: 67 56 
7: 67 56 
1: 67 56

我猜问题是在将值插入到集合中时出现的。我也认为,问题在某种程度上与“通过参考改变价值”有关。但不确定是什么原因造成的。我进行了更多实验,发现下面的代码片段有效。但是仍然不确定,上面的代码出了什么问题?

在下面的代码片段中,我制作了一个副本,而不是直接通过引用对其进行更新。然后插入我的值,然后再次将其复制到地图中,即可正常工作。

    vector<int> v = {1,us));
    }
    
    for (int i=0; i<v.size(); i++) {
        unordered_set<int> us = ump.find(v[i])->second;
        unordered_set<int> us1;
        for (auto it = us.begin(); it!=us.end(); it++) {
            us1.insert(*it);
        }
        us1.insert(67);
        ump.find(v[i])->second = us1;
    }

    for (auto it = ump.begin(); it != ump.end(); it++) {
        cout << it->first << ": ";
        for (auto ait = it->second.begin(); ait!=it->second.end(); ait++) {
            cout << *ait << ' ';
        }
        cout << '\n';
    }

这里的输出与预期的完全相同:

12: 67 56 
3: 67 56 
8: 67 56 
7: 67 56 
1: 67 56 

解决方法

unordered_set<int> us = ump.find(v[i])->second;

制作该集合的副本,以使您的修改不会更改ump中的值。您需要使用参考:

unordered_set<int>& us = ump.find(v[i])->second;

或使用auto

auto& us = ump.find(v[i])->second;

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