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
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.