I've seen people mention that a random element can be grabbed from an unordered_set in O(1) time. I attempted to do so with this:
std::unordered_set<TestObject*> test_set;
//fill with data
size_t index = rand() % test_set.size();
const TestObject* test = *(test_set.begin() + index);
However, unordered_set iterators don't support + with an integer. begin
can be given a size_t param, but it is the index of a bucket rather than an element. Randomly picking a bucket then randomly picking an element within it would result in a very unbalanced random distribution.
What's the secret to proper O(1) random access? If it matters, this is in VC++ 2010.
See Question&Answers more detail:os