I am using a std::unordered_map. I have a hash value and a way to determine if a given candidate key is the key that I am looking for, but I do not have an actual key. I want to
You cannot avoid constructing a key, but you can avoid constructing the entire key.
For example, let's say that you have a key class VectorKey
that encapsulates an std::vector
, and caches the computed hash code. Further suppose that you provide implementations of Hash
and KeyEqual
that access the cached hash code off your VectorKey
, and compare encapsulated vectors for equality. You can define a constructor of VectorKey
that always constructs an empty std::vector
, and sets the cached hash code to a value passed to the constructor:
class VectorKey{
int cached_hash;
std::vector<int> key;
public:
VectorKey(const std::vector<int>& _key)
: key(_key)
, cached_hash(calc_hash(_key)) {
}
// *** This is the centerpiece of the solution: ***
// *** this constructor effectively lets you access ***
// *** a bucket with nothing more than a hash code. ***
VectorKey(int hash)
: cached_hash(hash) {
}
// More code goes here for getting cached_hash
// and also for checking equality
private:
int calc_hash(const std::vector<int>& _key) {
// calculate the hash code based on the vector
}
};
With a key class like that, you can quickly find buckets by constructing a fake key:
size_type bucketIndex = myHashMap.bucket(VectorKey(precalculated_hash));