
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Difference Between std::vector and std::array in C++
Both vectors and arrays are used to store collections of elements, but they differ significantly in how they manage their memory and flexibility.
C++ std::vector
A vector is a dynamic array that can be resized automatically when elements are added or removed. It is a part of the C++ STL and provides more flexibility than a static array.
Example
In the following example, we will demonstrate the usage of the vector in C++ ?
#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; }
Following is the output of the code ?
The 2D vector is: 4 5 3 2 7 6 3 2 1 10
C++ std::array
An array is a fixed-sized contiguous block of memory that stores elements of the same data type. The size of the array must be assigned at compile time and can not be changed during runtime.
Example
In the following example, we will demonstrate the usage of the array in C++ ?
#include<iostream> #include<array> using namespace std; int main() { array < int, 4 > a = {10, 20, 30, 40}; cout << "The size of array is : "; cout << a.size() << endl; cout << "Maximum number of elements array can hold is : "; cout << a.max_size() << endl; cout << "The array elements are (using at()) : "; for (int i = 0; i < 4; i++) cout << a.at(i) << " "; cout << endl; a.fill(1); cout << "Array after filling operation is : "; for (int i = 0; i < 4; i++) cout << a[i] << " "; return 0; }
Following is the output of the code ?
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
Vector vs Array
Following are the key differences between vector and array ?
- A vector is a sequential container that stores elements and is not index-based, whereas an array is an index-based data structure that holds a fixed-size sequential collection of elements of the same type.
- A vector can dynamically change size as elements are added, while an array has a fixed size that cannot be resized once initialized.
- Vector occupies more memory. But the array is a memory-efficient data structure.
- Vector takes more time to access elements. Array access elements in constant time, irrespective of their location, as elements are arranged in a contiguous memory allocation.