Advantages of vector over array in C++


Here we will see some advantaged and disadvantages of vector over array in C++.

  • The vector is template class. This is C++ only constructs. The Arrays are built-in language construct. Arrays are present in different languages.

  • Vectors are implemented as dynamic arrays with list interface, arrays can be implemented using static or dynamic way with primitive datatypes.

Example

#include<iostream>
#include<vector>
using namespace std;
int main() {
   int array[10]; //statically allocated array
   int* arr = new int[10]; //dynamically allocated array
   vector<int> vec;
}
  • Array sizes are fixed. When one array is created, we cannot change the size. The size of the vector is dynamic. If we add new elements, if the place is not available, it creates new space for it, and some additional spaces.

  • If the arrays are allocated dynamically, then we have to deallocate it manually. But in vector we do not need to deallocate it, it automatically deallocates.

Example

#include<iostream>
#include<vector>
using namespace std;
int main() {
   int* arr = new int[10]; //dynamically allocated array
   delete(arr); //deallocate manually
   vector<int> vec; //will be deallocated when variable is out of scope
}
  • If we want to get the size of dynamically allocated array, we cannot get the size easily. For vectors, we can get the size in constant time.

  • If we want to send one array using function parameter, then we have to sendanother variable for size or length. If we send the vector, we do not need to pass some other variables.

  • We cannot return one array unless we use dynamically allocated new array, but we can return vectors from function.

Updated on: 20-Aug-2019

296 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements