Vectors

Steven J. Zeil

Old Dominion University, Dept. of Computer Science

Table of Contents

1. The Vector Interface
1.1. Constructors
1.2. Copying
1.3. Size & Capacity
1.4. Access to Elements
1.5. Inserting Elements
1.6. Removing Elements
2. Using Vectors
2.1. Keeping Authors in a Book
2.2. Vectorizing the book.h file
2.3. Vectorizing the book.cpp file
2.4. Vectors copy nicely
2.5. Completing the Book operations
3. Required Performance

A vector is similar to an array, except that it can "grow" to accommodate as many items as you actually try to put into it:

First, however, a slight digression into C++-isms. I stated earlier that A vector is similar to an array. The similarity comes from the fact that vectors keep their elements in numeric order and allow you to access them via indexing:

int a[];
vector<int> v;
   ⋮
a[i] = v[i+1];
     
string b[];
vector<string> w;
   ⋮
w[23] = "Hello";
     
Folderol c[];
vector<Folderol> x;
   ⋮
x[1] = c[1];
     

Because vectors are templates, we can have vectors containing almost any other type.

Why almost any type? You might remember that not every type can be used in an array. A type can only be used as array elements if that type provides a default constructor, because that constructor is used to initialize the elements of the array.

Similarly, types that are to be used as vector elements have a special requirement as well. This requirement is different from, but no more stringent than the requirement for arrays. Types to be used in a vector must supply a copy constructor. The textbook's implementation of vector actually goes beyond this, requiring a default constructor and an assignment operator as well, but these are not required in standard versions.


In the Forum:

(no threads at this time)