take_while.cpp 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. //
  10. // Project home: https://github.com/ericniebler/range-v3
  11. #include <vector>
  12. #include <range/v3/core.hpp>
  13. #include <range/v3/view/iota.hpp>
  14. #include <range/v3/view/generate.hpp>
  15. #include <range/v3/view/take_while.hpp>
  16. #include <range/v3/utility/copy.hpp>
  17. #include "../simple_test.hpp"
  18. #include "../test_utils.hpp"
  19. struct my_data
  20. {
  21. int i;
  22. };
  23. bool operator==(my_data left, my_data right)
  24. {
  25. return left.i == right.i;
  26. }
  27. int main()
  28. {
  29. using namespace ranges;
  30. auto rng0 = views::iota(10) | views::take_while([](int i) { return i != 25; });
  31. ::check_equal(rng0, {10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24});
  32. CPP_assert(view_<decltype(rng0)>);
  33. CPP_assert(!common_range<decltype(rng0)>);
  34. CPP_assert(random_access_iterator<decltype(rng0.begin())>);
  35. std::vector<int> vi{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
  36. auto rng1 = vi | views::take_while([](int i) { return i != 50; });
  37. CPP_assert(view_<decltype(rng1)>);
  38. CPP_assert(random_access_range<decltype(rng1)>);
  39. ::check_equal(rng1, {0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
  40. // Check with a mutable predicate
  41. int rgi[] = {0,1,2,3,4,5,6,7,8,9};
  42. int cnt = 0;
  43. auto mutable_only = views::take_while(rgi, [cnt](int) mutable { return ++cnt <= 5;});
  44. ::check_equal(mutable_only, {0,1,2,3,4});
  45. CPP_assert(view_<decltype(mutable_only)>);
  46. CPP_assert(!view_<decltype(mutable_only) const>);
  47. {
  48. auto ns = views::generate([]() mutable {
  49. static int N;
  50. return ++N;
  51. });
  52. auto rng = ns | views::take_while([](int i) { return i < 5; });
  53. ::check_equal(rng, {1,2,3,4});
  54. }
  55. {
  56. auto ns = views::generate([]() mutable {
  57. static int N;
  58. return ++N;
  59. });
  60. auto rng = ns | views::take_while([](int i) mutable { return i < 5; });
  61. ::check_equal(rng, {1,2,3,4});
  62. }
  63. {
  64. auto rng = debug_input_view<int const>{rgi} | views::take_while([](int i) {
  65. return i != 5;
  66. });
  67. ::check_equal(rng, {0,1,2,3,4});
  68. }
  69. {
  70. auto ns = views::generate([]() {
  71. static int N;
  72. return my_data{++N};
  73. });
  74. auto rng = ns | views::take_while([](int i) { return i < 5; },
  75. &my_data::i);
  76. ::check_equal(rng, std::vector<my_data>{{1},{2},{3},{4}});
  77. }
  78. return test_result();
  79. }