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?

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

hm.. so this is not yet standard? This is experimental code isn't it?
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).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.