Final answer:
In C++ 11, you can use a range-based for loop to modify the contents of an array without declaring the range variable as a reference.
Step-by-step explanation:
In C++ 11, you can use a range-based for loop to modify the contents of an array without declaring the range variable as a reference. The range-based for loop allows you to iterate over the elements of an array or any other iterable collection. However, if you want to modify the elements of the array in-place, you need to declare the range variable as a reference. Otherwise, the modifications will not affect the original array.
Here's an example:
#include <iostream>
int main() {
int arr[] = {1, 2, 3, 4, 5};
for(int& num : arr) {
num *= 2; // Modifying the elements in-place
}
for(int num : arr) {
std::cout << num << " "; // Output: 2 4 6 8 10
}
return 0;
}
In this example, the range-based for loop modifies the elements of the arr array by multiplying each element by 2. By declaring the range variable as a reference (int& num), the modifications are reflected in the original array. The output of the program confirms that the elements have been modified.