Code:

int arr[5] = { 1, 2, 3, 4, 5 }; for (auto i: arr) std::cout << "i" << "\n"; 

The question is why the numbering comes from one and not from scratch? Somehow it looks wrong, not to mention the fact that the cycle goes beyond the array. How to use a range-based loop for an array so that the numbering is from scratch, and not from one?

  • one
    Your loop goes through the elements of the array, the element with the zero index is 1, which you see on the output. - Vladimir Gamalyan

1 answer 1

The for (auto i: container) construct iterates through the elements of the container, not the indices, and is applicable even where there is no concept of an index — for example, in a hash table.

This expression can be viewed as unfolding in

 for(auto iterator = begin(container); iterator != end(container); ++iterator) { auto i = *iterator; 
  • Thank you, I set foot. Accustomed to the original cycles, I did not even think that it could be somehow different. - MikeNew