Vectors

Vectors#

C++ has the standard library (C++ SL) which adds an immense amount of functionality to the language. Let’s look at std::vector. A vector is a container that can hold data of the same type (e.g., double). It differs from an array that you might have used in other languages in that it is not a fixed size—it can grow as needed to hold more data.

Note

The C++ standard library was inspired by an earlier project called the C++ standard template library or STL. These are distinct, and for modern C++ we refer to the C++ standard library.

Note

There are many other types of containers in the C++ SL that have different properties.

Vectors are very useful to store data and loop over it, etc. Information on the properties of C++ vectors can be found at the CPlusPlus vector page. From that description, we see that vectors:

  • store the data contiguously in memory

  • can grow as needed (but occasionally, this means creating a new vector of larger size and copying data into it—a slow operation)

  • have a lot of functions that can work on them

  • can access any location directly

  • are very efficient at adding data to the end, but not efficient for inserting data in the middle

Creating a vector#

Lets see how to create a vector and add some data to it.

Here’s a simple example:

Listing 29 simple_vector.cpp#
#include <iostream>
#include <vector>

int main() {
    std::vector<double> container;

    container.push_back(10.0);
    container.push_back(-1.0);
    container.push_back(15.3);
    container.push_back(3.14159);

    std::cout << container[3] << std::endl;
    std::cout << "the vector has " << container.size() << " elements" << std::endl;

}

Notice the following:

  • We specify the data type when creating a vector

  • We use push_back to add data to the end of a vector. Here we are using the . operator to indicate that we are performing the push_back on the vector container that we created.

  • We access elements of a vector using [] with an index, and that indices start at 0.

  • We can use the .size() member function to get the number of elements in the vector.