Vectors

C++ lists and C++ vectors are both in a family of structures called sequence containers. These containers allow you to store values in series and then access those values. C++ has a handful of sequence containers including lists, vectors, and arrays.

Declaring C++ Vectors

std::vector<char> charactervectorvariable;
std::vector<int> integervectorvariable;
std::vector<float> floatvectorvariable;
std::vector<double> doublevectorvariable:

Including the Vector Library

In an actual program, you would need to include the vector file from the Standard Library:

#include <vector>

int main() {
      std::vector<float> floatvectorvariable;
      return 0;
}

Initializing Vector Values

In the previous part of the lesson, you learned to declare a vector first and then assign values:

vector<float> myvector(5);

myvector[0] = 5.0;
myvector[1] = 3.0;
myvector[2] = 2.7;
myvector[3] = 8.2;
myvector[4] = 7.9;

There are various other ways for assigning initial values to a vector. Here are two other ways:

Declaring and Defining Simultaneously

When declaring a vector, you can also assign initial values simultaneously.

std::vector<int> myvector (10, 6);

The code will declare a vector with ten elements, and each element will have the value 6.

Declaring and Defining Simultaneously with Brackets

There is another way to initialize a vector as well if you are using one of the more recent versions of C++ such as C++11 or C++17; You could also do something like:

std::vector<float> myvector = {5.0, 3.0, 2.7, 8.2, 7.9}

The different versions of C++ (C++98, C++11, C++14, and C++17) will be discussed in the Practical C++ lesson.

vector<T>::size_type is an implementation dependent type, which is usually size_t. Since it isn't specified by the standard and could potentially change, you should prefer to use it when you are dealing with elements of that type. For example, the type of vector<T>::size() returns a vector<T>::size_type. Thus, if you are iterating over the vector with an integral index, you would want this index to be of type vector<T>::size_type. This will ensure that your code is easy to maintain - if you decide to use a different implementation of the standard library, your code will be consistent.

size_type is a (static) member type of the type vector<int>. Usually, it is a typedef for std::size_t, which itself is usually a typedef for unsigned int or unsigned long long.

Last updated