2.1.2 Creating and Accessing Vectors

As mentioned earlier, vectors are a list of values making it easy to store multiple values in a single variable. Vectors are sequential, so you can access values by index and vectors are dynamic and can grow in size.

Creating Vectors

Vectors are declared using the keyword vector followed by the variable type inside of angled brackets.

vector<string> strVector;

Vectors can be created with or without initial values. To create with initial values, you list the initial values inside curly brackets after the vector name.

vector<int> intVector {1, 3, 5, 7, 9};

Note: In C++, you can optionally use an equals sign ,=, between the variable name and the initial value list. In the examples for this course I will not use that equal sign. Either way is considered an acceptable syntax.

While vectors are a part of the standard library, they are not included by default. Anytime you use a vector, you need to import them.

#include <vector>

Accessing Values in a Vector

Accessing values in a vector is pretty much the same as accessing individual characters in a string. Like strings, there are two ways to access elements in a vector, using .at(index) or with square brackets [index]. As with other things, vectors are zero indexed.

Access can be used to get a value as well as update a value.

vector<int> intVector {1, 3, 5, 7, 9};

cout << intVector.at(2); // Prints value at index 2: 5

intVector[3] = 11; // Updates value at index 3 to 11

While both methods will return value, square brackets provide an undefined behavior when accessing a value out of the range. It may crash your program, or it may return a garbage value.

When attempting to update values, both the .at() and [ ] will produce an error for an invalid index.

Last updated