We can use vector efficiently by taking care of following points,
1.) Vector will be more efficient if elements are inserted or removed from the back-end only.
As, vector internally stores all the elements in consecutive memory location. Therefore, if an element is added in middle, then vector right shifts all the right side elements of that location by 1. Also, if elements were user defined objects then copy constructors for all those elements are called.
Similarly If element is erased from the middle, then vector left shifts all the right side elements of that location by 1. Also, if elements were user defined objects then copy constructors for all those elements are called.
But if elements are inserted or deleted from the back-end only then this costly shifting will not happen.
2.) Set the storage of vector initially using reserve() member function.
As vector is a kind of container in which user can store unlimited elements. Internally it allocates storage to store the elements but during insertion if new memory requirement surpasses the current capacity then it allocates a bigger chunk of storage and copies all the existing elements there. It’s a huge burden for application because if elements in vector are user defined objects then in every new movement to new storage location copy constructor of elements will be called.
We can avoid this if in our application by reserving the vector capacity initially by calling reserve() function. This reserve() function requests the vector capacity to be at least enough to contain n elements. It only increases the vector’s capacity, size remains same.
3.) Instead of adding single element in multiple calls, large set of elements is added in single call
Pointers in C/C++ [Full Course]
Adding single element can cause,
- Shifting of some elements in vector
- Allocation of new memory and movement of all elements on new location
If we add a single element multiple times than all the above things can happen multiple times. Whereas, if we insert elements in together i.e. in a set than this shifting and copying can happen only once. vector can check if it has the capacity to store n elements or not or it needs to shift some elements by n location.