Using vector in c++ – How to Use Vector Efficiently in C++ ?

Using vector in c++: In the previous article, we have discussed about When to use virtual functions in C++?. Let us learn how to Use Vector Efficiently in C++ Program.

Using Vectors Efficiently in C++

We can use vectors efficiently by following the below guidelines-

Table of Content :

1. Insert or remove elements from the back-end only :

Vectors store all the elements in consecutive memory locations so if an element is added in the middle of the vector, it shifts all the elements to the right side. And if the elements are user defined objects then the vector has to call copy constructor for each of the elements individually.

A similar process takes place when a vector element is too be deleted from the middle. After deleting the element all the next elements are shifted to the left side. Similar;y for user defined objects the copy constructors are called.

Therefore it is suitable to use vectors at the back-end only to avoid the shifting of elements.

2. Initially using reserve() member function set the storage of vector :

Vectors are designed to store unlimited items in them. However a vector allocates the memory for it during initialization and if the memory needs surpasses the allocated memory, then it allocates a bigger memory set and then copies all the elements over there. And for user defined objects it calls the copy constructor individually for each object. This takes up almost double the memory space and adds lot of processes which is not efficient.

For this issue, we can use the reserve(n) function to reserve the capacity of the vector during initialization which would allocate sufficient memory for n elements and avoid the need of reallocating size in memory.

3. Add large set of elements in single call instead of adding single element in multiple calls :

If we add elements one-by-one into the vector we might cause the following-

  1. Repeated shifting of elements in vector for each individual element addition.
  2. Repeated allocation of a bigger memory and copying the data every time the required memory surpasses the allocated memory.

To avoid the repeated shifting of elements and reallocation of memory we can add elements together which will make the shifting a one time process and check if it is able to hold all the laments in the allocated memory or if it requires further allocation.