无法通过无序映射中的溢出进行交互

时间:2017-12-17 13:57:22

标签: c++ hash hashtable unordered-map

据我所知,boost:unordered_map和std :: unordered_map在“溢出”方面的工作方式相同(也就是用同一个键插入的多个东西)。它们将它存储在“桶”中,以便您可以迭代它们。

例如:

key:   data:
"apple" 2
"peach" 4
"apple" 3
"peach" 8

然后“苹果”的桶将包含2& 3,对吗?

好吧,我无法接受这些事情。

这是我的代码:

#define ANZ 10
typedef boost::unordered_map<uint16_t, int> uuidMap_int;


using namespace std;

int main()
{
    uuidMap_int uuidMap;
    boost::uuids::uuid entity1;
    boost::uuids::uuid entity2;

    for(unsigned int i = 0;i<ANZ;i++)
        uuidMap.insert(std::pair<int,int>((i<5?0:1),i));

    for(unsigned int i = 0;i < uuidMap.bucket_count();i++){
        for(uuidMap_int::local_iterator it = uuidMap.begin(i); it != uuidMap.end(i);++it){
            std::cout<<it->first<<"|"<<it->second<<"\n";
        }
    }
    return 0;
}

所有这一切都是为地图制作2个新条目并填充它们。 这是输出应该是什么样的:

0|0
0|1
0|2
.
.
.
1|5
1|6
.
.
.
1|10

但实际上看起来像这样

0|0
1|5

现在我不知道为什么会这样。似乎“溢出”只是被破坏了。但是我想把它变成一个小型的数据库,所以我需要一种方法来在这样的地图中拥有一个id和一堆属于所述id的数据。

我做错了什么/其他地图允许我以我想要的方式工作?

1 个答案:

答案 0 :(得分:0)

The problem (and what @juanchopanza tries to show) is that you have to read the documentation about a class, in order to use it correctly. A map is a relationship between a key (the indexing key) and a value (the data stored). In this case, you use only two keys (namely pip install https://dist.apache.org/repos/dist/dev/incubator/toree/0.2.0-incubating-rc2/toree-pip/toree-0.2.0.tar.gz and 0) and each 1 you do to the map just refuses to insert elements on the already two key cells with the new data. The expected behaviour is the one you get (you use only two different keys, you have only two cells with data), the first entries you inserted with the only two keys you have used, each. insert() classes allow you to have several entries with the same key, so you will get all your elements inserted properly.

But the other question that remains is why to use a Multimap if you don't use the functionality it offers to you. The map allows you to differentiate the elements by key, so normally, you don't insert (perhaps only in multimaps, where you cannot differentiate elements by key) but map the elements and index them by key (with the put() operator)?

Please, read thoroughly the documentation about each class.