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

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

    For std::unordered_set s:

    1) take random R in min(s)..max(s)

    2) if R in s: return R

    3)

    newIter = s.insert(R).first;
    newIter++;
    if (newIter == s.end()) {
        newIter = s.begin();
    }
    auto result = *newIter;
    s.erase(R);
    return result;
    

    For ordered set (std::set) probability would depend on distance between elements. unordered_set is randomized by hash.

    I hope this can help.

    PS converting std::set into std::set> (where first element in pair is a hash of second) makes this method suitable for any hashable V.

提交回复
热议问题