如何为 std::array 正确使用基于范围的 for 循环

How do I properly use a range-based for loop for an std::array

我可以使用传统的 for 循环和带有迭代器的传统 for 循环遍历数组,但是当我尝试使用基于范围的 for 循环时,我没有得到相同的结果。

#include <iostream>
#include <array>

int main() {
    std::array<int, 5> ar = {1, 2, 3, 4, 5};
    for(int i = 0; i < 5; i++) {
        std::cout << ar[i] << " ";
    }
    std::cout << std::endl;

    for(std::array<int, 5>::const_iterator it = ar.begin(); it != ar.end(); ++it) {
        std::cout << *it << " ";
    }
    std::cout << std::endl;

    for(const int& i: ar) {
        std::cout << ar[i] << " ";
    }
    std::cout << std::endl;
}
1 2 3 4 5 
1 2 3 4 5 
2 3 4 5 0

range-based for loopfor(const int& i: ar)中,i指的是元素而不是索引。所以

for(const int& i: ar) {
    std::cout << i << " ";
}