lundi 1 juin 2020

Displaying all elements of a vector

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.

Aucun commentaire:

Enregistrer un commentaire