When to use std::vector
vs std::array
When should I use std::vector
and when should I use std::array
in C++?
The choice between std::vector
and std::array
depends on your specific requirements:
Use std::vector
when:
- You need a resizable array whose size can change at runtime
- You don't know the number of elements at compile time
- You want to efficiently add or remove elements from the end of the array
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec{1, 2, 3};
vec.push_back(4);
std::cout << "Vector size: " << vec.size();
}
Vector size: 4
Use std::array
when:
- You know the number of elements at compile time
- You want a fixed-size array that cannot change size at runtime
- You want to avoid dynamic memory allocation overhead
#include <array>
#include <iostream>
int main() {
std::array<int, 3> arr{1, 2, 3};
// arr.push_back(4); // Compile error
std::cout << "Array size: " << arr.size();
}
Array size: 3
In general, prefer std::array
for fixed-size arrays and std::vector
for dynamic arrays.
Odds and Ends: 10 Useful Techniques
A quick tour of ten useful techniques in C++, covering dates, randomness, attributes and more