partial_sum.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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 <functional>
  12. #include <iterator>
  13. #include <range/v3/core.hpp>
  14. #include <range/v3/utility/copy.hpp>
  15. #include <range/v3/view/counted.hpp>
  16. #include <range/v3/view/partial_sum.hpp>
  17. #include <range/v3/view/reverse.hpp>
  18. #include "../simple_test.hpp"
  19. #include "../test_utils.hpp"
  20. int main()
  21. {
  22. using namespace ranges;
  23. int rgi[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  24. {
  25. auto rng = rgi | views::partial_sum;
  26. has_type<int &>(*begin(rgi));
  27. has_type<int>(*begin(rng));
  28. CPP_assert(view_<decltype(rng)>);
  29. CPP_assert(sized_range<decltype(rng)>);
  30. CPP_assert(forward_range<decltype(rng)>);
  31. CPP_assert(!bidirectional_range<decltype(rng)>);
  32. ::check_equal(rng, {1, 3, 6, 10, 15, 21, 28, 36, 45, 55});
  33. auto it = begin(rng);
  34. CHECK(*it == 1);
  35. auto it2 = next(it);
  36. CHECK(*it == 1);
  37. CHECK(*it2 == 3);
  38. it2 = it;
  39. CHECK(*it2 == 1);
  40. ++it2;
  41. CHECK(*it2 == 3);
  42. }
  43. {
  44. // Test partial_sum with a mutable lambda
  45. int cnt = 0;
  46. auto mutable_rng = views::partial_sum(rgi, [cnt](int i, int j) mutable { return i + j + cnt++;});
  47. ::check_equal(mutable_rng, {1, 3, 7, 13, 21, 31, 43, 57, 73, 91});
  48. CHECK(cnt == 0);
  49. CPP_assert(view_<decltype(mutable_rng)>);
  50. CPP_assert(!view_<decltype(mutable_rng) const>);
  51. }
  52. {
  53. auto rng = debug_input_view<int const>{rgi} | views::partial_sum;
  54. ::check_equal(rng, {1, 3, 6, 10, 15, 21, 28, 36, 45, 55});
  55. }
  56. {
  57. static int const some_ints[] = {0,1,2,3,4};
  58. auto t1 = ranges::views::partial_sum(some_ints);
  59. auto t2 = some_ints | ranges::views::partial_sum;
  60. ::check_equal(t1, t2);
  61. }
  62. return test_result();
  63. }