What is the difference between an array and a vector in C++?
| Point | C array | std::array | std::vector |
|---|---|---|---|
| Size | Fixed | Fixed | Changes at run time |
| Knows its size | No | Yes | Yes |
| Memory | Stack | Stack | Heap |
| Bounds check with at() | No | Yes | Yes |
| Add items | No | No | push_back |
#include <array>
#include <iostream>
#include <vector>
int main() {
int c[3] = {1, 2, 3};
std::array<int, 3> a = {1, 2, 3};
std::vector<int> v = {1, 2, 3};
v.push_back(4);
std::cout << sizeof(c) / sizeof(c[0]) << ' ' << a.size() << ' ' << v.size() << '\n';
}
Output
3 3 4
Learn more about the similar topics:
| Tutorials |
|---|
| C++ Strings: std::string and string_view |
| C++ Arrays and std::array |
| C++ Vectors (std::vector) |
| Exercises & Assignments |
|---|
| Reverse a string |
| Check if a string is a palindrome |
| Count the vowels in a string |
| Find the second largest number in a vector |
| Sort a vector with bubble sort |
| Transpose a matrix |
| Interview Questions & Answers |
|---|
| What is the difference between an array and a vector in C++? |
| What is the difference between std::string and a char array in C++? |