The STL Vector Class

By Alex Allain

One of the basic classes implemented by the Standard Template Library is the vector class. A vector is, essentially, a resizable array; the vector class allows random access via the [] operator, but adding an element anywhere but to the end of a vector causes some overhead as all of the elements are shuffled around to fit them correctly into memory. Fortunately, the memory requirements are equivalent to those of a normal array. The header file for the STL vector library is vector. (Note that when using C++, header files drop the .h; for C header files - e.g. stdlib.h - you should still include the .h.) Moreover, the vector class is part of the std namespace, so you must either prefix all references to the vector template with std:: or include "using namespace std;" at the top of your program.

Vectors are more powerful than arrays because the number of functions that are available for accessing and modifying vectors. Unfortunately, the [] operator still does not provide bounds checking. There is an alternative way of accessing the vector, using the function at, which does provide bounds checking at an additional cost. Let's take a look at several functions provided by the vector class:

unsigned int size();            Returns the number of elements in a vector
push_back(type element);        Adds an element to the end of a vector
bool empty();                   Returns true if the vector is empty
void clear();                   Erases all elements of the vector
type at(int n);                 Returns the element at index n, with bounds checking

also, there are several basic operators defined for the vector class:

=           Assignment replaces a vector's contents with the contents of another
==          An element by element comparison of two vectors
[]          Random access to an element of a vector (usage is similar to that
            of the operator with arrays.) Keep in mind that it does not provide
            bounds checking.

Let's take a look at an example program using the vector class:

#include <iostream>
#include <vector>

using namespace std;
int main()
    vector <int> example;         //Vector to store integers
    example.push_back(3);         //Add 3 onto the vector
    example.push_back(10);        //Add 10 to the end
    example.push_back(33);        //Add 33 to the end
    for(int x=0; x<example.size(); x++) 
        cout<<example[x]<<" ";    //Should output: 3 10 33
    if(!example.empty())          //Checks if empty
        example.clear();          //Clears vector
    vector <int> another_vector;  //Creates another vector to store integers
    another_vector.push_back(10); //Adds to end of vector
    example.push_back(10);        //Same
    if(example==another_vector)   //To show testing equality
    for(int y=0; y<example.size(); y++)
        cout<<example[y]<<" ";    //Should output 10 20
    return 0;

Summary of Vector Benefits

Vectors are somewhat easier to use than regular arrays. At the very least, they get around having to be resized constantly using new and delete. Furthermore, their immense flexibility - support for any datatype and support for automatic resizing when adding elements - and the other helpful included functions give them clear advantages to arrays.

Another argument for using vectors are that they help avoid memory leaks--you don't have to remember to free vectors, or worry about how to handle freeing a vector in the case of an exception. This simplifies program flow and helps you write tighter code. Finally, if you use the at() function to access the vector, you get bounds checking at the cost of a slight performance penalty.

Previous: Introduction to the STL
Next: Using Iterators to Access Containers (including vectors)
Related articles

Using templated classes in C++

Read about using iterators to access vectors and other collections