How to select a random element in std::set?

后端 未结 6 1331
北荒
北荒 2020-11-30 09:26

How can I select a random element in an std::set?

I naively tried this:

int GetSample(const std::set& s) {
  double r =          


        
6条回答
  •  春和景丽
    2020-11-30 10:06

    C++17 std::sample

    This will be a convenient, although not very efficient (O(n)) method:

    #include 
    #include 
    #include 
    #include 
    #include 
    
    int main() {
        std::set in{1, 2, 3, 5, 7};
        std::vector out;
        std::sample(in.begin(), in.end(), std::back_inserter(out),
                    3, std::mt19937{std::random_device{}()});
        for (auto i : out)
            std::cout << i << std::endl;
    }
    

    But I think that for efficiency you just need to copy to another type of structure: How to select a random element in std::set in less than O(n) time?

提交回复
热议问题