Is there a way to randomly retrieve an element from C++ unordered_set in O(1) average time? Instead of doing
std::unordered_set<int> s;
// initialize s
auto start = s.begin();
for (int i = 0; i < rand()%s.size()-1; ++i, ++start) {}
int randomNumber = *start;
Updated:
I need to fight for the post, so I add my reasons for needing the functionality of above.
I am playing with implementing a maze generator. And somehow I need a data structure which would support:
- insertion / deletion in O(1)
- random retrieve an element from the data structure in O(1)
std::vector has random access, but insertion / deletion is expensive
std::list has no random access
std::set support O(logN) random access, and O(logN) insertion/ deletion, which are great, but my initialization is a sorted sequence which would easily break the balance of it.
So I thought hash table would be the best choice, however randomly retrieval an element would be nontrivial.
Thank you for your time.