Advantages of vector over array in C++
We have already discussed arrays and vectors. In this post, we will discuss advantages of vector over normal array. Advantages of Vector over arrays :
- Vector is template class and is C++ only construct whereas arrays are built-in language construct and present in both C and C++.
- Vector are implemented as dynamic arrays with list interface whereas arrays can be implemented as statically or dynamically with primitive data type interface.
Size of arrays are fixed whereas the vectors are resizable i.e they can grow and shrink as vectors are allocated on heap memory.
Size of Array 100 Size of vector Before Removal=5 1 2 3 4 5 Size of vector After removal=4 1 2 4 5
Arrays have to be deallocated explicitly if defined dynamically whereas vectors are automatically de-allocated from heap memory.
Size of array cannot be determined if dynamically allocated whereas Size of the vector can be determined in O(1) time.
When arrays are passed to a function, a separate parameter for size is also passed whereas in case of passing a vector to a function, there is no such need as vector maintains variables which keeps track of size of container at all times.
Size of array= 2
When array becomes full and new elements are inserted; no reallocation is done implicitly whereas When vector becomes larger than its capacity, reallocation is done implicitly.
Arrays cannot be returned unless dynamically allocated from a function whereas vectors can be returned from a function.
warning: address of local variable 'arr' returned [-Wreturn-local-addr] Segmentation Fault (SIGSEGV)
1 2 3 4 5 6 7 8 9 10
Arrays cannot be copied or assigned directly whereas Vectors can be copied or assigned directly.
vector get: 1 2 3 4 5 6 7 8 9 10 error: invalid array assignment copyArr=arr;
Following are the list of advantages of vector over array:
- Resizing: Vectors can dynamically resize themselves, while arrays have a fixed size.
- Memory allocation: Vectors handle memory allocation and deallocation automatically, while arrays require manual management.
- Element access: Vectors provide direct access to elements using an iterator, while arrays require using an index.
- Sorting: Vectors provide built-in sorting functions, while arrays require manual sorting.
- Insertion and deletion: Vectors provide efficient insertions and deletions at the end, while arrays require shifting of elements.
- STL compatibility: Vectors are a part of the Standard Template Library (STL) and are compatible with other STL functions and algorithms.
- Exception handling: Vectors have built-in exception handling for out-of-bounds access, while arrays do not.
- Standardization: Vectors are a standardized feature of modern programming languages, and therefore more widely supported
- Memory utilization: Vector can save memory space if the number of elements increases after the array created by using dynamic memory allocation.