7

So with c++ 20 we get a lot of new features with ranges, spans and so on. Now if i need to iterate over a container, but only the first n elements, what would be the most appropriate way and is there any practical difference going on behind the scenes? Or is it perhaps a better idea to just go back to regular for loops with indexes as these examples might be less performant?

for (const auto &e: elements | std::ranges::views::take(n)) {
// do stuff
}

for (const auto &e: std::span(elements.begin(), n)) {
// do stuff
}

for (const auto &e: std::ranges::subrange(elements.begin(), elements.begin() + n)) {
// do stuff
}
Jane Doe
  • 480
  • 3
  • 15

1 Answers1

8
  • views::take is the most generic, it is suitable for almost any range, such as input_range, output_range, and more refined ranges.

  • std::span only applies to contiguous_range.

  • Although ranges::subrange is also generic, but since you need to obtain the bound of iterator through elements.begin() + n, this requires that the elements must be a random_access_range.

It is also worth noting that after P1739, views::take will get an "appropriate" range type according to the type of range, that is, when the range is span, it will return span, and when it is string_view, it will return string_view, and when it is subrange, it will return subrange, and when it is iota_view, it will return iota_view.

康桓瑋
  • 33,481
  • 5
  • 40
  • 90