Logic error with my for-for loop

I am learning 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 not understand why it does not 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 seem stupid, but I'm new. If I try to do the same with traditionally for the loop, it works, why?

+4
source share
6 answers

It does not change the value in the array, because in each iteration, the value in the array is assigned x, and you change x, not the value in the array.

Basically, a range-based loop is similar to the following regular loop:

for(int i = 0; i < numbers.length(); i++)
{
     int x = numbers[i];

     //your code
}

.

++: http://en.cppreference.com/w/cpp/language/range-for. :

range_expression . , , , range_declaration.

"Shmil The Cat" , , .

+3
for (int& x : numbers) x = 0; 

, ( )

+3

, foreach. , numbers x, . , x , .

@Shmil The Cat. , .

+1

(), , .

for (int& x : numbers) x = 0; 

@Shmil The Cat

+1

, :

For each element in numbers, copy the data to x and set x to 0.//Now this does not apply to the value in the vector.

for (int x : numbers) 
    x = 0; 

Reading the bottom loop:
For each element in numbers, make a reference to it and change the value using the reference to 0. This, on the other hand, changes the values ​​in the vector.

for (int &x : numbers)
    x = 0;
0
source

If you want to set a specific value for all elements, it would be better to use std::fill

std::fill(numbers.begin(), numbers.end(), 0);
0
source

Source: https://habr.com/ru/post/1568613/


All Articles