Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logic error with my range-for loop

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 ?

like image 342
piero borrelli Avatar asked Feb 11 '23 07:02

piero borrelli


1 Answers

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.

like image 161
scigor Avatar answered Feb 18 '23 23:02

scigor