Vectors - sheerazwalid/COMP-I GitHub Wiki
You can think of vectors in C++ as arrays whose size you can change at runtime. Vectors are instances of a vector class so there is also additional functionality specific to arrays that can be invoked through the dot operator.
Like an array, a vector is a container of values of some data type. So when you create an instance of the vector class, you need to specify the type of data it will store. The following shows the syntax used for creating a vector of int and compares that with the syntax used for creating an array of int.
int a[20]; // Create an array that holds 20 ints.
vector<int> v(20); // Create a vector of ints with an initial size of 20.
Unlike arrays, the number of elements contained in a vector can change. The following code shows how to create a vector of int with initialize size of 0, and then expand the size of the vector to 1 to store a 3, and then expand the size to 2 to store a 7.
vector<int> v; // v = ( )
v.push_back(3); // v = ( 3 )
v.push_back(7); // v = ( 3, 7 )
You can access the size of a vector using the size function as illustrated in the following.
vector<int> v; // v = ( )
cout << v.size(); // prints 0
v.push_back(3); // v = ( 3 )
cout << v.size(); // prints 1
v.push_back(7); // v = ( 3, 7 )
cout << v.size(); // prints 2
Another useful function is pop_back.
vector<int> v; // v = ( )
v.push_back(3); // v = ( 3 )
v.push_back(7); // v = ( 3, 7 )
v.pop_back(); // v = ( 3 )
v.pop_back(); // v = ( )
There are many other functions in the vector class but size, push_back and pop_back are the most important for this course.