What is the advantage of multimap over vector display?

I do not understand why multimap exists if we can create a vector map or a map of sets. For me, there are only differences:

  • using equal_range in multimap to get the key elements and in the vector map, we just use the [] operator and have a vector of elements.
  • using multimap.insert(make_pair(key,value)) in multimap to add elements and map_of_vectors[key].push_back(value) to the vector map.

So why use multimap? It's better for me to have a vector than two iterators to get all the key values.

This question also applies to unordered_map vectors and unordered_multimap.

+55
c ++ multimap stl map
Dec 14 '10 at 9:52
source share
3 answers

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

So, for example, do you often look at all the elements with the X key or pass them to functions, and so on? Then it’s more convenient to already have them in a separate container, which you can address directly.

However, if you only have a set of elements that can share the same key value, or not, why use vectors between them? It is more convenient to run through multimap with iterators than to have a nested loop for a map, a vector register.

Another way to look at this: if several key entries are very common, your structure is more efficient in a map, vector case. If they are rarely, it's the other way around.

+43
Dec 14 '10 at 10:07
source share

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

After you have inserted the value in multimap, you know that the iterator will remain valid until you delete it, and this is a very strong property, you cannot have it with a vector map.

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

The iterator remains valid until it is removed from the map, and in the second case, it will be invalidated every time you add a new record to the vector.

Also note that map<x, vector<y>> may have null values ​​set with an existing key, whereas multimap does not.

These are different things that behave differently.

And frankly, I skip multimap in some languages ​​that don't provide it in my library.

+41
Dec 14 '10 at
source share

two iterators ??? I think you're wrong.

when I use std :: for_each () or another algo from multimap, I use only ONE range of iterators, and this is much easier than worrying about a vector for each key.

-one
Dec 14 '10 at 10:06
source share



All Articles