【发布时间】:2017-03-19 08:11:55
【问题描述】:
我是 C++ 新手,对 unordered_map(或 hash_map)有以下问题:
#include <unordered_map>
#include <iostream>
using namespace std;
int main()
{
unordered_map<int,int> h1;
int temp1=0;
h1.insert(pair<int,int>(0,temp1));
unordered_map<int, unordered_map<int,int>> h2;
h2.insert(pair<int, unordered_map<int,int>>(1,h1));
unordered_map<int, unordered_map<int,int>>::iterator h2_itor=h2.find(1);
h2_itor->second.find(0)->second++;
unordered_map<int, unordered_map<int,int>> h3;
for(int i=0;i<100;i++)
{
int first=rand()%10;
int second=rand()%10;
unordered_map<int, unordered_map<int,int>>::iterator h3_itor=h3.find(first);
if(h3_itor!=h3.end())
{
unordered_map<int,int> submap=h3_itor->second;
unordered_map<int,int>::iterator submap_itor=submap.find(second);
if(submap_itor!=submap.end())
submap_itor->second++;
else
submap.insert(pair<int,int>(second, 1));
}
else
{
unordered_map<int,int> submap;
submap.insert(pair<int,int>(second,1));
h3.insert(pair<int, unordered_map<int,int>>(first,submap));
}
}
return 0;
}
输出很奇怪。对于 h1 和 h2 似乎有效,这意味着 h1 中键为 0 的值已更新(递增 1)。虽然这看起来微不足道,但对于 h3,我随机插入一些“对”(第一,第二)并使用哈希图进行计数,但计数似乎无法更新。比如可能是这样的:
insert 1 -> 7 -> 1
...
now update 1 -> 7 -> 1 to 1 -> 7 -> 2 using my code
fetch: h3.find(1)->second.find(7)->second : it's still 1 but not 2!
表示更新值不成功。我知道在 Java 中这永远不会发生。那么这个问题出在哪里呢?
【问题讨论】:
-
我发现很难遵循测试程序的逻辑。你能把问题减少到 5 或 6 行代码吗?
-
@Richard Hodges 我已经改进了代码以使其更短。 h1 和 h2 的逻辑是将 h1 作为带有某个(随机)键的值插入到 h2 中,然后尝试更新 h1 中某个项目的值(将 h1 本身作为 h2 的一个项目)。基本思想是看是否可以更新哈希映射的子映射。 (虽然听起来微不足道。)h3 的逻辑也是一个“嵌套”的哈希映射。我在其中随机插入一些子图,以及一些随机项到这些子图中,看看值是否可以更新。
-
修改后的程序不会尝试产生任何输出,因此预期输出(空)与实际输出(也是空)相同。这在我的书中按预期工作。请阅读minimal reproducible example。
标签: c++ hashmap unordered-map