3
votes

First for loop

  int i;
  for (i = 0; i <= vec.size(); i++) {
    if (vec.size() == 0) {
      cout << "[] The list is Empty" << endl;
    } else {
      cout << vec[i] << " ";
    }
  }
}

Second for loop

cout << "[ ";
for(auto num : vec)
  cout << num << " ";
cout << "]";

Why is it that when I display all the elements in a vector using the first for loop I get "0" at the end of the vector. However, when I use the range for loop, I do not get the zero.

1
also vec.size() gives you unsigned int - dgrandm

1 Answers

5
votes

In the first loop, when i reaches vec.size(), vec[i] is out of bounds of vec, which leads to undefined behaviour (UB). You need to change the loop condition from i<=vec.size() to i<vec.size().

Also, your check for vec.size() == 0 inside of the loop will never be true. That check needs to be moved above the loop.

if (vec.size() == 0) {
    cout << "[] The list is Empty" << endl;
}
for (i=0; i<vec.size(); i++) {
    cout <<vec[i] << " ";
}

On the other hand, ranged-based for loop iterates over all the elements exactly and keep us away from such troubles.