I have a few integer keys that is needed to retrieve a value. What is the most efficient way to store and retrieve the value based on the keys?
Currently I am converting and combining the three keys into a single string and store the key-value pair in a map. However, I think there should be a more efficient way of doing that based on the integer value alone for example generating a single key based on the three keys. Any ideas on that?
Thanks.
You can almost certainly do better than converting to a string (which is generally quite a slow operation). If your three items have small enough ranges, you can do some shifting and adding to put them together into a single integer with a larger range.
Lacking that, you can just create a struct that holds three ints, and defines
operator<to compare them in a reasonable fashion:Edit: for those who care about it, using (std | tr1 | boost)::tuple wouldn’t change the character of answer much, but would eliminate most of the code. A tuple is pretty similar to
std::pair, except that it supports an arbitrary number of items instead of just two. For the example above, you could use something like:tupledefines comparison operators automatically assuming the types are comparable (i.e., for comparing two tuples with the same number of elements, and the types of corresponding elements are comparable). In this case it does a lexicographic comparison (i.e., the result of the comparison is the result from the first pair of corresponding elements that are not equal — of no such element exists, the two compare equal).