Skip to content

Index Range

An IndexRange (source) represents a set of non-negative consecutive indices. It's stored as just the start index and the number of indices. Since it's small, it should generally be passed by value.

The most common usage of IndexRange is to loop over indices. This is better than a c-style index loop because it reduces the likelyhood of mixing up variables and allows the current index to be const. It's also just more convenient.

/* Iterate over the indices from 0 to 9. */
for (const int64_t i : IndexRange(10)) { /* ... */ }

Most container data structures have an .index_range() method which makes it easy to iterate over all the indices in the container.

/* Iterate over indices in the container. */
Vector<int> vec = /* ... */;
for (const int64_t i : vec.index_range()) { /* ... */ }

/* Iterate over the indices but skip the first 5. */
for (const int64_t i : vec.index_range().drop_front(5)) { /* ... */ }