Vectors were a new concept to me, and all the online resources were so detailed and technical and overwhelming. So, I'm going to try to make this as simple as possible.
A Vector is a one dimensional array, but the difference is that vectors can automatically grow or decrease in size as the program runs. i.e. its a dynamic array.
This can be useful in a lot of situations, for example, when you're receiving user input and you don't know in advance how many lines they will enter. Then, you can use a vector to store new lines as they come in, because they can expand in size to accommodate new information.
To declare a vector, we simply use:
vector <int> myVectorName (2) ;
Well the size is optional. You can just stop with vector <int> myVectorName where vector is the definition, <int> is the data type of vector, so you can also have string vectors, float vectors, etc. And finally myVectorName is the Variable Name for the newly created vector.
In raw syntax format, it would look like this:
vector <datatype> variable (elements) ;
Their storage is handled automatically by the C++ container. (A container is just a builtin C++ object that is a collection of other objects, i.e. its elements. A container also handles memory for its elements, and offers member functions through iterators. Some container class templates are: arrays, vector, list, set, map, queue, etc)
This means we don't have to directly allocate space, we can just set a maximum or minimum value (if we want), or nothing at all.
In Vectors, data is inserted at the end. This is usually done using push_back, which is used to insert elements at the end of the vector.
vector <int> v1, v2;
for(int i=0;i<=5;i++)
v1.push_back(i);
v1.begin() returns a pointer to the start of the vector, and v1.end() for the end of the vector. Similarly, v1.rbegin() returns a pointer to the reverse beginning (i.e. the end) of the array and v1.rend() for the reverse end (i.e. the beginning) of the array. These can be used to access the elements:vector <int> v1;
for(int i=0;i<=10;i++)
v1.push_back(i);
cout << "Print the Vector: ";
for (auto i = v1.cbegin(); i != v1.cend(); ++i)
cout << *i << " ";
cout << "\\n";
cout << "Print the Vector in reverse: ";
for (auto i = v1.rbegin(); i != v1.rend(); ++i)
cout << *i << " ";
-----------------------------------------------------------------
Print the Vector: 0 1 2 3 4 5 6 7 8 9 10
Print the Vector in reverse: 10 9 8 7 6 5 4 3 2 1 0
[Finished in 0.50s]
*note that auto in c++ automatically decides the variable type for you.
Let's define a simple function that we can call to print vectors for us: