Comparing Vector and Array: Understanding the Key Differences
Written by
Vector vs Array
One of the common questions that arise in the minds of young coders is what are the differences between vectors and arrays and which one is better among the two? After this post, there won’t even a strand of doubt in your minds
- Vector is a template class available in only C++ WHEREAS array is a primitive data-type available in both C and C++
- Vectors are implemented as dynamic arrays with list interface WHEREAS array can be implemented as statically or dynamically with primitive data type
- Vectors being objects of class are passed by value until passed by reference WHEREAS arrays are by default passed by reference
- Vectors are resizable i.e. their size grows and shrinks with insertion and deletion WHEREAS array are of fixed size, once set, it can be changed
- Vectors occupy more space for their ability to dynamically change their size as compared to arrays which are more memory efficient
- Vectors are deallocated automatically WHEREAS we have to explicitly deallocate arrays if defined dynamically
- Vectors provide many functions such as sizeof(), sort(), and help shorten the code which are not available for arrays
- Size of vectors can be determined in O(1) time by size() function WHEREAS size of array can’t be determined if dynamically allocated
- Vectors can’t be copied or assigned directly WHEREAS arrays can.
- Vectors can be returned by a function WHEREAS arrays can’t unless dynamically allocated by a function
- To access elements, Vectors take more time as compared to arrays