Sal Rosa
Sal Rosa

Reputation: 601

Why don't these range based for loops work properly?

The output is 2 3 4 5 2293456 6 10 1355995651 12980632 0

it seems i is not incrementing properly

#include <iostream>
#include <vector>
using namespace std;
int main()
{
    int x[5] = {1,2,3,4,5};

    vector<int> vec = {2, 4, 6, 8, 10};

    for(int i : x) {
        cout<<x[i]<<endl;
    }

    cout<<endl;

    for(int i : vec) {
        cout<<vec[i]<<endl;
    }
}

Upvotes: 1

Views: 127

Answers (1)

Nicol Bolas
Nicol Bolas

Reputation: 473437

When you use range-based for loops, you're getting the values in the container, not the indices in the container. So i is a value from inside the array/vector, not the index.

Remember: range-based for loops work on containers that don't have indices, like std::list, std::map, and so forth. They work on arbitrary iterator ranges of values.

Upvotes: 7

Related Questions