Difference between std::array and std::vector in C++
The std::vector is a container that implements a dynamic array and the std::array implements the static array. In this article, we shall learn the difference between std::array and std::vector.
Before we start looking at the differences, I would like to emphasize the internal implementation of these containers.
The std::vector is a dynamic array which means that we can change and modify the size in the runtime of the program. So, we mostly choose the vector in most applications.
The std::array is a static array implementation. We have to fix the size of the atd::array while writing the program that is the size should be a compile-time constant.
The following example of the declaration of these two containers gives an obvious distinction:
// Online C++ compiler to run C++ program online
#include <iostream>
#include <vector>
#include<array>
template<typename T>
void print(T a) // a common function template to print vector and array
{
for(auto r:a)
{
std::cout<<r<<" ";
}
std::cout<<std::endl;
}
int main() {
std::vector<int> a(4); //vector declared with size 4
std::array<int,4> ar; //array with size 4
for(int i=0;i<4;i++)
{
ar[i]=i; a[i]=i;
}
a.push_back(5); // add extra elements in the vector
//We cant add more than 4 elements in the std::array
std::cout<<"vector :";
print(a);
std::cout<<"array :";
print(ar);
}OUTPUT:
vector :0 1 2 3 5 array :0 1 2 3
Having understood the main difference in implementation, now we shall look at other differences
Differences between std::array and std::vector:
- We can increase or decrease std::vector size in runtime as required. Whereas, We must specify the size of the array in runtime.
- The std::vector has push_back() and insert() functions to add elements dynamically(can be added whenever required). But we cannot add extra elements to an array and it doesn’t have any push_back() function.
- The std::vector can be used to substitute a std::array. But, we can’t do it the other way.
- The insert time in std::array is constant whereas it is amortized constant in vector.
- std::array instantiates a class from the template for every size. Whereas, the vector instantiates a class for the particular datatype. Therefore I recommend not using std::array with many different sizes (in the order of millions of sizes), because this will cause a huge compile time.
- std::vector includes all the functions that std::array has but the array doesn’t have vector functions (eg. push_back() and pop_back())
In conclusion, I would suggest you use the std::array whenever the size of the sequence is constant and the std::vector for dynamic sizes. We, can still use the std::vector for constant size sequence but compared to ats::array the std::vector uses more resources like memory and processing.
Leave a Reply