多重映射比矢量映射有什么优势?

我不明白为什么多重映射存在,如果我们可以创建向量映射或集合映射。 对我来说,唯一的区别是:

  • 在 Multimap 中使用 equal_range来获取键的元素,在向量映射中我们简单地使用 []算子,得到元素的向量。
  • 在多重映射中使用 multimap.insert(make_pair(key,value))添加元素,在向量映射中使用 map_of_vectors[key].push_back(value)

那么为什么要使用多重映射呢?对我来说,用一个向量比用两个迭代器得到一个键的所有值要好。

这个问题也适用于向量的 unorder _ map 和 unorder _ multimap。

22627 次浏览

I would say it depends on whether all the values with same key have a relationship that you want to address.

So for example, do you often go through all elements with key X, or pass them to a function, and so on? Then it is more convenient to already have them in their separate container, that you can address directly.

However, if you just have a collection of items, that may share same key value, or not, why use vectors in between? It is more convenient to run through the multimap with iterators than have a nested for-loop for the map, vector case.

Another way of looking at this: If multiple entries per key is very common, your structure is more efficient in the map, vector case. If they seldomly happen, it is the opposite.

There are many important differences between multimap<x, y> and map<x, vector<y>>

Once you had inserted a value into multimap, you know that the iterator would remain valid until you remove it and this is very strong property, you can't have it with map of vectors.

multimap<x,y>::iterator p=mymap.insert(make_pair(a,b));

The iterator remains valid until it is erased from map, while in second case, it would be invalidated each time you add new entry to the vector.

Also note that map<x, vector<y>> may have an empty value set with existing key, while multimap does not.

These are different things that behave differently.

And to be honest I miss multimap in some languages that do not provide it in their library.