Search code examples
c++for-loopvisual-c++outofrangeexceptionrange-based-loop

Can you avoid out of range error if you use range based for loop instead of the standard for loop?


I was experimenting around with range-based for loop found that if you use range-based for loop to loop through a vector it runs into out of range error is there any way to avoid this error if you are using range-based for loop

int main()
{
    vector<int> num{ 1,2,3,4,5 };
    for (auto i : num)
    {
        cout << num[i] << endl;
    }
}

it shows this error

enter image description here


Solution

  • It's nothing to do with the type of loop. Your loop looks at all the values i inside the vector num, then it prints num[i]. One of them is 5, so it prints num[5]. But num has 5 elements so they only go up to num[4]. Out of range.