Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over a part of an array in a range-based loop

Tags:

c++

arrays

c++11

Is there any way to iterate over only a part of an array in the C++11 range-based loop? Say I have an int someArray[10000000] but I only want to iterate over the first n elements. Thus, I can't simply use

for(auto elem: someArray) {//doStuff}

Any way to limit the scope of the loop while still using the range-based goodies?

like image 900
Straightfw Avatar asked Oct 21 '15 19:10

Straightfw


1 Answers

Simply adapt the range to be a different type where begin() and end() do the right thing.

struct Slice {
  int* arr;
  size_t n;
  int* begin() { return arr; }
  int* end() { return arr + n; }
};

for(auto elem : Slice{someArray, 100}) {/*doStuff*/}
like image 110
Jonathan Wakely Avatar answered Oct 06 '22 10:10

Jonathan Wakely