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

后端 未结 5 932
[愿得一人]
[愿得一人] 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:18

    You may be able to make a randomly-ordered copy of the map by using this constructor

    template 
    set(InputIterator f, InputIterator l,
        const key_compare& comp)
    

    ..and passing a comparator that compares hashes of the keys (or some other deterministic spreading function.) Then take the "smallest" keys according to this new map.

    You could construct the map once and amortize the cost across several requests for a "random" element.

提交回复
热议问题