订购 unordered_map c++ 时数据丢失

Loss of data while ordering an unordered_map c++

我有一个 unordered_map<string, int> freq 我命令它把它变成一个 map<int,string> freq2。我使用下一个函数来做到这一点:

map<int, string> order(unordered_map<string, int> x) {
    map <int, string> map;
    for (auto it = x.begin(); it != x.end(); ++it) {
        map.emplace(it->second, it->first);
    }

    return map;
}

unordered_map 的大小是 2355831 而返回的 map 是 505,所以你看到数据丢失相当大,我不知道为什么...... 知道为什么会这样吗?

谢谢。

编辑:

感谢大家,你们都很好,我有很多具有相同值的 int,这就是为什么我丢失了数据(我真的很愚蠢,以前没有看到它)

代码本身看起来不错。但是,由于您是从字符串键映射到整数,因此您最好有多个具有相同值的键。

来自 emplace 的文档:

The insertion only takes place if no other element in the container has a key equivalent to the one being emplaced (keys in a map container are unique).

因此,如果您在第一个地图中的许多条目具有相同的值(这是第二个地图中的键),那么您的数据集将减少很多。

如果您需要保留这些元素,那么 std::map 不是正确的容器。

这很可能是因为 int 值之间存在重复。尝试将 map<int, string> 替换为 multimap<int, string>.