If you want to associate a value with an index and quickly find the index, you can use std::map
or std::unordered_map
. You can also combine them with other data structures (for example, std::list
or std::vector
) depending on other operations that you want to perform on the data.
For example, when creating a vector, we also create a lookup table:
vector<int> test(test_size); unordered_map<int, size_t> lookup; int value = 0; for(size_t index = 0; index < test_size; ++index) { test[index] = value; lookup[value] = index; value += rand()%100+1; }
Now, to look at the index, you simply:
size_t index = lookup[find_value];
Using a hashtable-based data structure (like unordered_map) is a pretty classic space / time trade-off and can outperform performing binary searches for this kind of βreverseβ lookup operation when you need to search a lot. Another advantage is that it also works when the vector is unsorted.
For fun :-) I did a quick test in VS2012RC, comparing James binary search code with linear search and using unordered_map to search, all on the vector:
Up to ~ 50,000 elements of unordered_value (x3-4) surpasses binary search, which demonstrates the expected behavior of O (log N), a somewhat unexpected result is that unordered_map loses O (1) behavior for 10,000 elements, presumably to hash collisions, possibly to the problem of implementation.
EDIT: max_load_factor () for an unordered map is 1, so there should be no collisions. The performance difference between the binary search and the hash table for very large vectors seems to be related to caching and varies depending on the search pattern in the benchmark.
Choosing between std :: map and std :: unordered_map talks about the difference between ordered and unordered maps.