How to select a random element in std::set in less than O(n) time?

后端 未结 5 931
[愿得一人]
[愿得一人] 2021-01-01 20:30

This question with an added constraint.

I\'m willing to allow not-uniform selection as long as it\'s not to lop sided.

Given that \"sets are typically imple

5条回答
  •  感情败类
    2021-01-01 21:04

    I don't see how to do it with just std::set, so you probably need a different data structure. Like Victor Sorokin said, you can combine a set with a vector. Instead of set, use map, plus vector< map::iterator >. The value for each key is an index into the vector, and each element of the vector points back to the map element. The vector elements have no particular order. When you add an element, put it at the end of the vector. When you remove an element and it's not the last one in the vector, move the last element to the deleted element's position.

提交回复
热议问题