fork(1) download
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. #include <random>
  5.  
  6. int main() {
  7. std::vector<int> data{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  8. std::vector<int> sample_result(3);
  9.  
  10. // Check for the presence of the __cpp_lib_sample macro (appeared in C++17)
  11. #if __cpp_lib_sample
  12. std::cout << "Using std::sample from C++17." << std::endl;
  13. std::sample(data.begin(), data.end(), sample_result.begin(), sample_result.size(), std::mt19937{std::random_device{}()});
  14. #else
  15. std::cout << "std::sample is not supported. Using alternative method." << std::endl;
  16. // Alternative code for older standards (e.g., manual shuffle and copy)
  17. std::random_device rd;
  18. std::mt19937 g(rd());
  19. std::shuffle(data.begin(), data.end(), g);
  20. std::copy_n(data.begin(), sample_result.size(), sample_result.begin());
  21. #endif
  22.  
  23. std::cout << "Selected elements: ";
  24. for (int n : sample_result) {
  25. std::cout << n << " ";
  26. }
  27. std::cout << '\n';
  28.  
  29. return 0;
  30. }
  31.  
Success #stdin #stdout 0.01s 5272KB
stdin
Standard input is empty
stdout
std::sample is not supported. Using alternative method.
Selected elements: 6 2 9