Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird issue with range based for loop

I am working on learning vectors in my C++ object oriented 1 class and we have been introduced the concept of range based for loops. I decided to practice the range based for-loops separately so that I could get used to the syntax but I came across a weird issue.

 #include<iostream>
 using namespace std;
 int main()
 {
   int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
   for ( auto i: a)
     {
       cout << a[i] << " ";
     }

 return 0;
 } 

When I run the above code my output is the following.

2 3 4 5 6 7 8 9 0 1 Press any key to continue...

My output should read

1 2 3 4 5 6 7 8 9 0 Press any key to continue...

Can anyone tell me why my first index is skipped? I have visual studio 2013 professional.

like image 643
Callat Avatar asked Jul 25 '26 18:07

Callat


1 Answers

You get the weird output because i in the range loop is the value from the array, not an index. That is,

for (auto i : a)

loops through the values of a. In your code you're effectively printing the sequence a[a[0]], a[a[1]], etc.

The code you probably want is

for (auto i : a) {
    std::cout << i << std::endl;
}
like image 132
blazs Avatar answered Jul 28 '26 10:07

blazs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!