sort.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Range v3 library
  2. //
  3. // Copyright Eric Niebler 2014-present
  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 <array>
  10. #include <random>
  11. #include <vector>
  12. #include <range/v3/core.hpp>
  13. #include <range/v3/view/iota.hpp>
  14. #include <range/v3/view/stride.hpp>
  15. #include <range/v3/view/take.hpp>
  16. #include <range/v3/algorithm/shuffle.hpp>
  17. #include <range/v3/algorithm/copy.hpp>
  18. #include <range/v3/algorithm/move.hpp>
  19. #include <range/v3/algorithm/is_sorted.hpp>
  20. #include <range/v3/algorithm/equal.hpp>
  21. #include <range/v3/action/shuffle.hpp>
  22. #include <range/v3/action/sort.hpp>
  23. #include "../simple_test.hpp"
  24. #include "../test_utils.hpp"
  25. int main()
  26. {
  27. using namespace ranges;
  28. std::mt19937 gen;
  29. auto v = views::ints(0,100) | to<std::vector>();
  30. v |= actions::shuffle(gen);
  31. CHECK(!is_sorted(v));
  32. auto v2 = v | copy | actions::sort;
  33. CHECK(size(v2) == size(v));
  34. CHECK(is_sorted(v2));
  35. CHECK(!is_sorted(v));
  36. CPP_assert(same_as<decltype(v), decltype(v2)>);
  37. v |= actions::sort;
  38. CHECK(is_sorted(v));
  39. v |= actions::shuffle(gen);
  40. CHECK(!is_sorted(v));
  41. v = v | move | actions::sort(std::less<int>());
  42. CHECK(is_sorted(v));
  43. CHECK(equal(v, v2));
  44. // Container algorithms can also be called directly
  45. // in which case they take and return by reference
  46. shuffle(v, gen);
  47. CHECK(!is_sorted(v));
  48. auto & v3 = actions::sort(v);
  49. CHECK(is_sorted(v));
  50. CHECK(&v3 == &v);
  51. auto r = views::ref(v);
  52. r |= actions::sort;
  53. // Can pipe a view to a "container" algorithm.
  54. actions::sort(v, std::greater<int>());
  55. v | views::stride(2) | actions::sort;
  56. check_equal(views::take(v, 10), {1,98,3,96,5,94,7,92,9,90});
  57. return ::test_result();
  58. }