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
}
CodePudding user response:
views::takeis the most generic, it is suitable for almost any range, such asinput_range,output_range, and more refined ranges.std::spanonly applies tocontiguous_range.Although
ranges::subrangeis also generic, but since you need to obtain the bound of iterator throughelements.begin() n, this requires that theelementsmust be arandom_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.
