How can I select a random element in an std::set
?
I naively tried this:
int GetSample(const std::set& s) {
double r =
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?