sample.stable.pass.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. //===----------------------------------------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. // UNSUPPORTED: c++98, c++03, c++11, c++14
  9. // <algorithm>
  10. // template <class PopulationIterator, class SampleIterator, class Distance,
  11. // class UniformRandomNumberGenerator>
  12. // SampleIterator sample(PopulationIterator first, PopulationIterator last,
  13. // SampleIterator out, Distance n,
  14. // UniformRandomNumberGenerator &&g);
  15. #include <algorithm>
  16. #include <random>
  17. #include <cassert>
  18. #include "test_macros.h"
  19. #include "test_iterators.h"
  20. // Stable if and only if PopulationIterator meets the requirements of a
  21. // ForwardIterator type.
  22. template <class PopulationIterator, class SampleIterator>
  23. void test_stability(bool expect_stable) {
  24. const unsigned kPopulationSize = 100;
  25. int ia[kPopulationSize];
  26. for (unsigned i = 0; i < kPopulationSize; ++i)
  27. ia[i] = i;
  28. PopulationIterator first(ia);
  29. PopulationIterator last(ia + kPopulationSize);
  30. const unsigned kSampleSize = 20;
  31. int oa[kPopulationSize];
  32. SampleIterator out(oa);
  33. std::minstd_rand g;
  34. const int kIterations = 1000;
  35. bool unstable = false;
  36. for (int i = 0; i < kIterations; ++i) {
  37. std::sample(first, last, out, kSampleSize, g);
  38. unstable |= !std::is_sorted(oa, oa + kSampleSize);
  39. }
  40. assert(expect_stable == !unstable);
  41. }
  42. int main(int, char**) {
  43. test_stability<forward_iterator<int *>, output_iterator<int *> >(true);
  44. test_stability<input_iterator<int *>, random_access_iterator<int *> >(false);
  45. return 0;
  46. }