For the past few days, I have been trying to finish the 11th grade portion of C++ in my tutorials and move onto some, more interesting (or rather, more advanced) topics. Here’s one: Vectors. I thought that it’d be best to bring the concept of vectors right after arrays, when the mind is fresh about that idea. The main thing to think about a vector is that the size of a vector is variable. Most books (or, at least the one I refer to, an old version of C++ Primer) already teach vectors before teaching about arrays, which I feel isn’t for the best. Arrays are more down-to-earth than vectors, and I believe that it would be in the best interest of everyone to learn it first and then come this way.
A vector is a collection of objects of a single type, each of which has an associated integer index. As with strings, the library takes care of managing the memory associated with storing the elements. We speak of a vector as a container because it contains other objects. All of the objects in a container must have the same type. - C++ Primer, 4th Edition.
As I have said before and as you can see from that definition, a vector is a collection of objects (much like an array), but the main difference is that the vector data type (I’m really regretting this post) is variable. Which is to mean, that you have an array, but with variable size.
Declaring and Initialisation
||vector that holds objects of type T;|
|Default constructor v1 is empty|
||v2 is a copy of v1|
||v3 has n elements with value i|
||v4 has n copies of a value-initialized object|
vectors Grow Dynamically
A central property of vectors is that they are required to be implemented so that it is efficient to add elements to them at run time. Because vectors grow efficiently, it is usually best to let the vector grow by adding elements to it dynamically as the element values are known.¹
This tutorial has excerpts from a book that I personally like very much, and it is this.