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.

## Vectors

A vector is a set of values where each value is identified by a number (called an index). An pstring is similar to a vector, since it is made up of an indexed set of characters. The nice thing about vectors is that they can be made up of any type of element, including basic types like ints and doubles, and user-defined types like Point and Time.

The vector type that appears on the AP exam is called pvector. In order to use it, you have to include the header file pvector.h; again, the details of how to do that depend on your programming environment.

You can create a vector the same way you create other variable types:

pvector<int> count;
pvector<double> doubleVector;

The type that makes up the vector appears in angle brackets (< and >). The first line creates a vector of integers named count; the second creates a vector of doubles. Although these statements are legal, they are not very useful because they create vectors that have no elements (their length is zero). It is more common to specify the length of the vector in parentheses:

pvector<int> count (4);

The syntax here is a little odd; it looks like a combination of a variable declarations and a function call. In fact, that's exactly what it is. The function we are invoking is an pvector constructor. A constructor is a special function that creates new objects and initializes their instance variables. In this case, the constructor takes a single argument, which is the size of the new vector.

The following figure shows how vectors are represented in state diagrams:

The large numbers inside the boxes are the elements of the vector. The small numbers outside the boxes are the indices used to identify each box. When you allocate a new vector, the elements are not initialized. They could contain any values.

There is another constructor for pvectors that takes two parameters; the second is a "fill value," the value that will be assigned to each of the elements.

pvector<int> count (4, 0);

This statement creates a vector of four elements and initializes all of them to zero.

Last Update: 2005-11-21