I was using auto function in my program when I got this error "Error: This range based for loop requires a begin function and none was found." How can I use for constant integers, as shown in my example below:
You can only use the ranged based loops with arrays when the size of the array is known (in the same scope as it was declared). When you pass an array to a function you can no longer use a range based loop, or the sizeof operator because you only have the address of the array available.
Note: the question is about range-based loop, unlike the thread title.
You do explicitly decay the array to a pointer and pointers do not know whether they have invalid address, address of one object, or address of one object that is in an array. The
1 2 3 4 5 6 7 8 9
for ( auto &i : size ) {
std::cout << arr[i] << " ";
}
// is like writing
for ( auto it = std::begin(size); it != std::end(size); ++it ) {
auto & i = *it;
std::cout << arr[i] << " ";
}
It should be obvious why that has issues.
One can always use the older for syntax:
1 2 3
for ( int i = 0; i < size; ++i ) {
std::cout << arr[i] << " ";
}
One could use algorithm and lambda to emphasize the for each element in array nature of the function:
1 2
std::for_each( arr, arr+size, []( auto x ) {
std::cout << x << " "; } );