I am able able to get the difference between the array and vector .Why we need vector if array is there?
Vector STL need of the vector
Hello @sudhanshu8917,
- Vector are implemented as dynamic arrays with list interface whereas arrays can be implemented as statically or dynamically with primitive data type interface.
Example:
int array[100]; // Static Implementation int* arr = new int[100]; // Dynamic Implementation vector<int> v; // Vector's Implementation
-
Size of arrays is fixed whereas the vectors are resizable i.e they can grow and shrink as vectors are allocated on heap memory.
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 have to be deallocated explicitly if defined dynamically whereas vectors are automatically de-allocated from heap memory.
So, in case of an array, there is a chance of memory leak. -
Size of an 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 the size of the container at all times.
-
Arrays cannot be returned unless dynamically allocated from a function whereas vectors can be returned from a function.
-
Arrays cannot be copied or assigned directly whereas Vectors can be copied or assigned directly
Hope, this would help.
Give a like, if you are satisfied.