Search code examples
c++c++11mingwmingw-w64

Range based for loop starts at one instead of zero?


I have just started using range based for loops to simplify my code when using templates. I have come across a strange error and am not sure if this is something that I am missing or if the compiler is making a mistake. I have written a piece of code to illustrate the issue that I am having as well as the output. These are shown below.

Note: I am using the Mingw64 compiler on windows g++ (rev5, Built by MinGW-W64 project) 4.8.1 compiled without optimization with the --std=c++11 flag.

Code:

#include <iostream>
#include <array>
#include <vector>

int  main()
{
    // Declares an array of size 5 and of type int and intialises.
    std::array<int,5> x = {1,2,3,4,5};
    std::vector<int> y = {1,2,3,4,5};

    // Prints each element
    std::cout << "Array:" << std::endl;
    std::cout << "x" << "\t" << "i" << std::endl;
    for (auto i  : x)
    {
        std::cout << x[i] << "\t" << i << std::endl;
    }

    std::cout << "Vector" << std::endl;
    std::cout << "y" << "\t" << "i" << std::endl;
    for (auto i : y)
    {
        std::cout << y[i] << "\t" << i << std::endl;
    }
    std::cin.get();
    std::cin.get();
    return 0;
}

Output:

Array:
x       i
2       1
3       2
4       3
5       4
0       5
Vector
y       i
2       1
3       2
4       3
5       4
1313429340      5

I would assume that the last line of both the vector and array output is an overflow, and notice how i starts at one instead of zero?? I would have assumed it would behave as described here.


Solution

  • I think you have not understood the syntax correctly

    for (auto i  : x)
    

    here i is not an index of an array, it is the actual element inside the vector x. So it is doing its job correctly.