The C++Course provides a general introduction to programming in C++. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details.


Vector Length

There are only a couple of functions you can invoke on an pvector. One of them is very useful, though: length. Not surprisingly, it returns the length of the vector (the number of elements).

It is a good idea to use this value as the upper bound of a loop, rather than a constant. That way, if the size of the vector changes, you won't have to go through the program changing all the loops; they will work correctly for any size vector.

  for (int i = 0; i < count.length(); i++) {
    cout << count[i] << endl;
  }

The last time the body of the loop gets executed, the value of i is count.length() - 1, which is the index of the last element. When i is equal to count.length(), the condition fails and the body is not executed, which is a good thing, since it would cause a run-time error.


Last Update: 2005-12-05