2

Is there any way to do a range-based for loop of part of a vector? For instance, I'd like to iterate over the first 5 elements of the vector:

for(auto& elem : my_vector[0:5]) {  // Syntax obviously doesn't exist
  do_stuff(elem);
}

I could write my own container as specified in How to make my custom type to work with "range-based for loops"? but I'm hoping that there is an easier way in boost or some related library.

C++20 appears to include "ranges", but is there anything similar before 20?

Thomas Johnson
  • 10,776
  • 18
  • 60
  • 98

1 Answers1

4

The de facto standard (library) for this is range-v3 — here's how it looks:

for (auto& elem : ranges::view::slice(my_vector, 0, 5)) { ... }
// or
for (auto& elem : ranges::view::take(my_vector, 5)) { ... }

If you need range support in C++03, Boost.Range is an alternative, though its implementation is rather rudimentary in comparison.

ildjarn
  • 62,044
  • 9
  • 127
  • 211
  • hm.. so this is not yet standard? This is experimental code isn't it? –  May 26 '18 at 18:36
  • 2
    No, not yet; but C++20 adds `std::span<>` which will allow this (but only for contiguous ranges like `std::vector<>`), and hopefully ranges as well (though not likely the views that are used here). – ildjarn May 26 '18 at 18:38