I'm studying C++ as a beginner (I started 2 months ago) and I have a problem with my simple code. I tried to set the value of each element in this vector to 0 but I can't understand why it doesn't work :
vector<int> numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for (int x : numbers) x = 0;
I know that I may sound stupid but I am a beginner. If I try to do the same thing with a traditionally for loop it works, why ?
It does not change the values in the array, because in each iteration the value in the array is assigned to to x and you are changing x and not the value in the array.
Basically the range based loop is similar to the following ordinary for loop:
for(int i = 0; i < numbers.length(); i++)
{
int x = numbers[i];
//your code
}
.
For more information check out the c++ documentation: http://en.cppreference.com/w/cpp/language/range-for . It states:
range_expression is evaluated to determine the sequence or range to iterate. Each element of the sequence, in turn, is dereferenced and assigned to the variable with the type and name given in range_declaration.
Also you will find there the example "Shmil The Cat" has posted and more examples which will help you understand how the range loop works.
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