简体   繁体   中英

Where to implement the hash function?

I am using an object as a key in an unordered_map , so I need to define a hash function. My question is, where should the hash function be implemented. Should I put it with the class implementation or should I implement it close to where I need it.

UPDATE: If it makes a difference, all of this is based in a framework

If you anticipate you'll need to reuse it in many unordered_map s, put it somewhere visible, like in the class.

If you just need it for a one-off unordered_map , put it close to where you use it. You can even use a lambda .

I'd put it with the class definition, at least if you're using == as the equality function in the unordered_map . The implementation of the hash function depends on the implementation of the equality comparison, and there is a definite advantage in keeping both together, to reduce the probability of someone not changing the hash function if they change == .

If you're also defining a special equality function for the map, then the two functions should be defined together, probably close to where they will be used to instantiate the map.

In my opinion if the hash function is basic as below it should be method of the class and also should be inline.

int hashFunction(long x){
    return (int) (x % N);
}

If it is a little more complex hash function it should be a method of this class.Because you will need a "N" which will be spesific to that class .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM