Initialize Vector in C++
A vector can store multiple data values like arrays, but they can only store object references and not primitive data types. They store an object's reference means that they point to the objects that contain the data, instead of storing them. Unlike an array, vectors need not be initialized with size. They have the flexibility to adjust according to the number of object references, which is possible because their storage is handled automatically by the container. The container will keep an internal copy of alloc, which is used to allocate storage for lifetime. Vectors can be located and traversed using iterators, so they are placed in contiguous storage. Vector has safety features also, which saves programs from crashing, unlike Array. We can give reserve space to vector, but not to arrays. An array is not a class, but a vector is a class. In vector, elements can be deleted, but not in arrays.
With the parent 'Collection class,' vector is sent in the form of a template class. The array is the lower level data structure with their specific properties. Vectors have functions & constructors; they are not index-based. They are the opposite of Arrays, which are index-based data structures. Here, the lowest address is provided to the first element, and the highest address is provided to the last element. Vector is used for insertion and deletion of an object, whereas Arrays used for frequent access of objects. Arrays are memory saving data structures, while Vector utilizes much more memory in exchange to manage storage and grow dynamically. Vector takes more time to access the elements, but this not the case with Arrays.
There are four ways of initializing a vector in C++:
By entering the values one-by-one -
All the elements in a vector can be inserted one-by-one using the vector class method 'push_back.'
Using an overloaded constructor -
When a vector has multiple elements with the same values, then we use this method.
By using an overloaded constructor of the vector class -
This method is mainly used when a vector is filled with multiple elements with the same value.
8 8 8 8 8 8 8 8 8 8 8 8
By the help of arrays -
We pass an array to the constructor of the vector class. The Array contains the elements which will fill the vector.
9 8 7 6 5 4 3 2 1 0
Using another initialized vector -
Here, we have to pass the begin() and end() iterators of an initialized vector to a vector class constructor. Then we initialize a new vector and fill it with the old vector.
1 2 3 4 5 6 7 8