shuffle.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Range v3 library
  2. //
  3. // Copyright Filip Matzner 2015
  4. //
  5. // Use, modification and distribution is subject to the
  6. // Boost Software License, Version 1.0. (See accompanying
  7. // file LICENSE_1_0.txt or copy at
  8. // http://www.boost.org/LICENSE_1_0.txt)
  9. #include <vector>
  10. #include <random>
  11. #include <range/v3/core.hpp>
  12. #include <range/v3/view/iota.hpp>
  13. #include <range/v3/view/stride.hpp>
  14. #include <range/v3/algorithm/copy.hpp>
  15. #include <range/v3/algorithm/move.hpp>
  16. #include <range/v3/algorithm/is_sorted.hpp>
  17. #include <range/v3/algorithm/equal.hpp>
  18. #include <range/v3/algorithm/sort.hpp>
  19. #include <range/v3/action/shuffle.hpp>
  20. #include "../simple_test.hpp"
  21. #include "../test_utils.hpp"
  22. int main()
  23. {
  24. using namespace ranges;
  25. std::mt19937 gen;
  26. // "Ints" view vs. shuffled
  27. auto v = views::ints(0,100) | to<std::vector>();
  28. auto v2 = v | copy | actions::shuffle(gen);
  29. CHECK(is_sorted(v));
  30. CHECK(!is_sorted(v2));
  31. CHECK(size(v2) == size(v));
  32. CPP_assert(same_as<decltype(v), decltype(v2)>);
  33. CHECK(!equal(v, v2));
  34. // "Ints" view vs. shuffled and sorted
  35. sort(v2);
  36. CHECK(is_sorted(v2));
  37. CHECK(equal(v, v2));
  38. // Shuffled vs. shuffled
  39. v |= actions::shuffle(gen);
  40. v2 = v2 | move | actions::shuffle(gen);
  41. CHECK(!is_sorted(v));
  42. CHECK(!is_sorted(v2));
  43. CHECK(size(v2) == size(v));
  44. CHECK(!equal(v, v2));
  45. // Container algorithms can also be called directly
  46. // in which case they take and return by reference
  47. v = views::ints(0,100) | to<std::vector>();
  48. auto & v3 = actions::shuffle(v, gen);
  49. CHECK(!is_sorted(v));
  50. CHECK(&v3 == &v);
  51. // Create and shuffle container reference
  52. v = views::ints(0,100) | to<std::vector>();
  53. auto r = views::ref(v);
  54. r |= actions::shuffle(gen);
  55. CHECK(!is_sorted(v));
  56. // Can pipe a view to a "container" algorithm.
  57. v = views::ints(0,100) | to<std::vector>();
  58. v | views::stride(2) | actions::shuffle(gen);
  59. CHECK(!is_sorted(v));
  60. return ::test_result();
  61. }