Using arrays to store a collection of variables, even objects, if very beneficial. However, it does have some limitations given that arrays are of a fixed size, and cannot shrink or grow with use. This means you either run out of space after a set of time, or you waste a lot of space as it is partitioned, but not used. Neither of these is good.
There is a templated class called the vector, which helps you get around this. It can be accessed just like an array, but it can grow with use if more space is needed.
vector<dataType> vectorName; // generalized syntax to create a vector
If you pass a parameter to it, you define an initial size for the vector, like so:
vector<dataType> vectorName(10); // generalized syntax to create a vector with 10 units
Given that we can create a series of different vectors, here are some examples:
Note: You will need to include the vector library to get this to work however. (#include <vector>
)
vector<int> intVector; // creates a vector of integers
vector<double> dblVector(10); // creates a vector of 10 doubles
vector<string> stringVector; // a vector of strings
vector<Circle> circleVector; // yes you can use user defined data types in a vector
If you pass a second parameter, you define a default value. Let’s create a Vector with 10 items in it, defaulting to 100.
vector<int> intVector(10,100);
You can access values in a vector by using the bracket notation like you do an array.
vector<int> intVector(10,100);
for int i = 0; i < 10; i++)
{
cout << intVector[i] << endl;
}
Vector Functions
push_back(element) – adds the element to the vector, at the end
pop_back() – removes the last element of the vector
size() – returns an int for the size of your vector
at(index) – returns the element at that index.
empty() – returns a boolean value if the vector is empty
clear() deletes all of the elements in the vector
The Vector Class was originally found on Access 2 Learn