I need a c++ memory dictionary container, that get a key, and return a value any way.
That is, if the key doesn’t exist in the ‘keys list’, it will find the most similar key, and give the value.
Any suggestions?
EDIT:
Thank for the comments.
More details:
For Simplicity, let’s start with numeric key. If the key is within 200 distance from the key, get it.
You need to use something called locality-sensitive hashing, and you’ll need to write a little bit of code on top of it (just a tiny bit, I promise. One extra word).
First, you need to use
std::mapand notstd::unordered_mapor any other hash table – it has to be a tree or other ordered data structure.Your key would be the locality-sensitive hash, which has the behavior of hashing similar inputs to close outputs. So the hash of AAA and the hash of AAB would be closer together than the hash of AAA and CCC. The value would be whatever you want it to be.
To retrieve the “nearest match”, you just need to use the
std::map::lower_bound(orstd::map::upper_bound) to get the nearest value to any given input from the map.So your code would look like this
Done and done.
Some Notes:
This is assuming a non-numberic key. Numbers are already “locale-sensitive hashes” of themselves, i.e. if
H(n)isn, the difference betweenH(n)andH(n')is directly proportional to the difference between inputsnandn'. In that case,lower_boundis the only thing you need, and you don’t need the extra hashing step.You can extend this method very easily to do things like specify a maximum distance between objects. This will depend on the locale sensitive hash you’re using and how it signifies the distance between two hashes for two given inputs, but generally just compare
H(n)andH(n')before returning thenearest_struct(withnearest_structbeingn').