Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intersection of two unordered_maps

Basically my question is the same as Intersection of two STL maps, but with two unordered_maps:

std::unordered_map<Key, Value> A;
std::unordered_map<Key, Value> B;

I'd like get the intersection, something similar to

std::unordered_map<Key, std::pair<Value, Value>> C;

where the keys are the values in both A and B and the value is a pair of the values from A and B respectively.

What is the fastest way to achieve this? Currently I iterate over the smallest of both and query for the key in the second. Fortunately often my key type is quite simple to hash, but I did not find a means to get the hash value of my key of the iterated map to spare the computation of the hash for the second (to be clear: I don't know how to recover the hash without recomputing it again, and where to find something like find with a computed hash as argument [1]).

Thanks.

[1] Yeah, I know, early optimization is the root of plenty of diseases. Yet I'd like to know if this is possible, not an explanation about how this would be a can of bugs. And actually, in some cases, depending on user input, the keys can be complex and costly to hash.

like image 213
akim Avatar asked May 04 '26 04:05

akim


1 Answers

I know you don't want to hear it, but I'm going to say it anyway: you should cache the hash value on the instances so that hashing reduces to simple member lookup. If the instances are immutable (or at least, the parts that go into the hash function are immutable), then the easiest way to do this is to compute the hash in the constructor.

like image 154
Fred Foo Avatar answered May 06 '26 21:05

Fred Foo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!