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?
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*/}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With