0

I can iterate through the array with a traditional for loop and a traditional for loop with iterators, but when I try to use a ranged-based for loop, I do not get the same result.

#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

1 Answer 1

3

In range-based for loop for(const int& i: ar), i refers to element but not index. So

for(const int& i: ar) {
    std::cout << i << " ";
}
Sign up to request clarification or add additional context in comments.

3 Comments

And there's not much point using for(const int& i: ... here. for(int i: ... is more efficient (passing by value is more efficient than passing by reference for primitive types, since it avoids an extra dereference and the copy is cheap).
@PaulSanders Does the compiler optimized out the unnecessary reference here?
@prehistoricpenguin Most likely, yes. But why take the chance? Coding the loop with a reference here is just silly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.