Lesson 9 – Vectors

In the previous lesson, we learnt about arrays. Arrays are containers that store data. In order to declare an array, you need to specify what type of data it stores, and the array cannot be used to store any other data types. You will also need to declare the size of the array. Once initiated, the array cannot change the number of data it stores.

In many situations, we would like to dynamically add or delete data from our array. Think of a contact list. You may want to add more contacts, or remove some that are no longer relevant. In such situations, you could use a modified kind of array to store the data. This data type is called a vector.

Declaring vector

To use a vector, you will need to include the <vector> in the preprocessor. vector is contained inside the C++ Standard Template Library (STL). You may need to use many STL data structures in writing complicated programs.

#include <vector>

Read the C++ documentation for vector.

The two very important methods of vector class is push_back() and pop_back(). push_back() adds a new data to the end of the vector while pop_back() removes the last data from the vector. at() allows you to access the data at the particular index.

std::vector<int> my_vector = {4, 6, 8};
std::cout << my_vector[1] << std::endl;

The output is 6 because it has in index of 1.

Challenge 1

Modify the program in Lesson 8 to use vector class. This allows you to store any number of records in your program.

Challenge 2

List all the natural numbers below 1000 that are multiples of 3 or 5. Store these numbers in a vector. Sum up all these numbers.

The correct answer is 233168.