3

To remove manual logic in my code, I use that construct:

std::ranges::drop_view a { std::ranges::take_view(my_range, my_range.size() -X), Y};

with X and Y values I pass at runtime.

Even though I check the algorithms, I could not find a shorter way that has the following constraints:

  1. don't go beyond or below the range I want, and don't do anything if the range has 0 elements -> no overflow
  2. non owning -> no copies

ranges::subranges doesn't meet those requirements.

Thanks

Kroma
  • 1,109
  • 9
  • 18
  • There's really no reason to write `drop_view` and `take_view` in code. This is: `auto a = my_range | views::take(my_range.size() - X) | views::drop(Y)`. Or `auto a = views::drop(views::take(my_range, my_range.size() - X), Y);` Note that `views::take(r, n)` isn't always a `take_view`. – Barry Jul 05 '22 at 15:00

1 Answers1

1

You can compose take_view and drop_view into a new adaptor

auto take_and_drop = [](auto n, auto m) {
  return std::views::take(n) | std::views::drop(m);
};

auto a = my_range | take_and_drop(my_range.size() - X, Y);
康桓瑋
  • 33,481
  • 5
  • 40
  • 90
  • `my_range.size() - X` has type `std::size_t`, so if `X > size()`, you don't have expected behaviour (`n` would have big value instead of negative one). – Jarod42 Jul 05 '22 at 11:11
  • @Jarod42: that case is already handled by the library by checking the length of the container. No issues here: U(ranges::begin(e), ranges::begin(e) + std::min(ranges::distance(e), f)) – Kroma Jul 05 '22 at 11:20
  • @Kroma: I would expect an empty view when `X > size()`, not a full view or UB. – Jarod42 Jul 11 '22 at 17:11