Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Each Element of a multimap Contain Both the Key and Value?

I can't imagine this hasn't been asked, but I'm not having any luck finding it.

Does each element of a multimap contain its value and its key?

That is does the internal structure of a multimap look like more like this:

map<key, vector<value>>

Or more like this:

vector<pair<key, value>>
like image 643
Jonathan Mee Avatar asked Apr 06 '18 14:04

Jonathan Mee


People also ask

How does multimap determine value by key?

We can find all values of a key in Multimap using is member function equal_range(). It accepts the key as an argument and returns a pair of multimap iterator. This returned pair has a range that represents the entries with given key.

Can multimap have duplicate keys?

Multi-map in C++ is an associative container like map. It internally store elements in key value pair. But unlike map which store only unique keys, multimap can have duplicate keys.

What is a multimap data structure?

In computer science, a multimap (sometimes also multihash, multidict or multidictionary) is a generalization of a map or associative array abstract data type in which more than one value may be associated with and returned for a given key.

Are the values in a multimap sorted?

Multimap is an associative container that contains a sorted list of key-value pairs, while permitting multiple entries with the same key. Sorting is done according to the comparison function Compare , applied to the keys.


1 Answers

Each element contains both its key and value.

You can tell because iteration returns a stable non-allocating reference to std::pair<Key const, Value>.

What more, Keys can compare equal but be different. A multimap permits you to store "extra data" in that Key that isn't part of the ordering, and you'll get it back afterwards and it will be associated with that Value.

Implementing a multimap as a std::map<Key, std::vector<Value>> is an option that is sometimes better than using a std::multimap<Key,Value>. Especially with many-values per key, it will be more memory efficient, have better locality, etc. Iterating over it can be trickier if you want to do so uniformly, but if you want to iterate over things clumped by key it is easier.

like image 117
Yakk - Adam Nevraumont Avatar answered Oct 22 '22 08:10

Yakk - Adam Nevraumont