I have two elements (6 and 747) that share their key ("eggs"). I want to find all the elements that share a key (let's say "eggs", but I would in real life do that for every key). How to do that?
There must be a way to get a container or something back from the data structure . . .
You're still mistaking key's value with key's hash. But to answer question as asked: you can use
unordered_map
'sbucket()
member function with bucket iterators:demo
In simple and mostly correct terms, unordered containers imitate their ordered counterparts in terms of interface. That means that if a
map
will not allow you to have duplicate keys, then neither willunordered_map
.unordered
do employ hashing function to speed up the lookup, but if two keys have the same hash, they will not necessarily have the same value. To keep the behaviour similar to the ordered containers,unordered_set
andunordered_map
will only consider elements equal when they're actually equal (usingoperator==
or provided comparator), not when their hashed values collide.To put things in perspective, let's assume that
"eggs"
and"chicken"
have the same hash value and that there's no equality checking. Then the following code would be "correct":But if you want allow duplicate keys in the same map, simply use
unordered_multimap
.Unordered map does not have elements that share a key.
Unordered multi map does.
Use
umm.equal_range(key)
to get apair
of iterators describing the elements in the map that match a given key.However, note that "collision" when talking about hashed containers usually refers to elements with the same hashed key, not the same key.
Also, consider using a
unordered_map<key, std::vector<value>>
instead of a multimap.