Difference between std::vector and std::array in C++

C++Server Side ProgrammingProgramming

The following are the differences between vector and array −

  • Vector is a sequential container to store elements and not index based.
  • Array stores a fixed-size sequential collection of elements of the same type and it is index based.
  • Vector is dynamic in nature so, size increases with insertion of elements.
  • As array is fixed size, once initialized can’t be resized.
  • Vector occupies more memory.
  • Array is memory efficient data structure.
  • Vector takes more time in accessing elements.
  • Array access elements in constant time irrespective of their location as elements are arranged in a contiguous memory allocation.

Vectors and arrays can be declared with the following syntax −

Vector declaration:vector<datatype>array name;
Array declaration:type array_name[array_size];
Vector initialization:vector<datatype>array name={values};
Array initialization:datatype arrayname[arraysize] = {values};

std::vector:

Example Code

#include <iostream>
#include <vector>
using namespace std;
int main() {
   vector<vector<int>>v{ { 4, 5, 3 }, { 2, 7, 6 }, { 3, 2, 1 ,10 } };
   cout<<"the 2D vector is:"<<endl;
   for (int i = 0; i < v.size(); i++) {
      for (int j = 0; j < v[i].size(); j++)
         cout << v[i][j] << " ";
         cout << endl;
   }
   return 0;
}

Output

the 2D vector is:
4 5 3
2 7 6
3 2 1 10

std:: array:

Example Code

#include<iostream>
#include<array>
using namespace std;

int main() {
   array<int,4>a = {10, 20, 30, 40};
   cout << "The size of array is : ";
   //size of the array using size()
   cout << a.size() << endl;
   //maximum no of elements of the array
   cout << "Maximum number of elements array can hold is : ";
   cout << a.max_size() << endl;
   // Printing array elements using at()
   cout << "The array elements are (using at()) : ";
   for ( int i=0; i<4; i++)
      cout << a.at(i) << " ";
      cout << endl;
      // Filling array with 1
      a.fill(1);
      // Displaying array after filling
      cout << "Array after filling operation is : ";
   for ( int i=0; i<4; i++)
      cout << a[i] << " ";
      return 0;
}

Output

The size of array is : 4
Maximum number of elements array can hold is : 4
The array elements are (using at()) : 10 20 30 40
Array after filling operation is : 1 1 1 1
raja
Published on 03-Apr-2019 17:20:50
Advertisements