No, you cannot change the size of a std::array
after it has been created. The size of a std::array
is fixed at compile time, which means it must be known when you write your code and cannot be changed while your program is running.
This is one of the key differences between std::array
and std::vector
. A std::vector
can dynamically change its size at runtime, while a std::array
 cannot.
Here's an example that illustrates this:
#include <array>
int main() {
std::array<int, 3> MyArray{1, 2, 3};
MyArray.resize(5);
}
error: 'resize': is not a member of 'std::array'
This code will not compile because std::array
does not have a resize
function. The size of MyArray
is fixed at 3 and cannot be changed.
If you need a container whose size can change at runtime, you should use std::vector
 instead:
#include <vector>
int main() {
std::vector<int> MyVector{1, 2, 3};
MyVector.resize(5);
}
Here, MyVector
starts with a size of 3, but we can resize it to 5 (or any other size) as needed.
The fixed size of std::array
can be an advantage in certain situations. Because the size is known at compile time, std::array
can be stored on the stack, which is typically faster than the heap storage used by std::vector
. Also, the fixed size means that std::array
doesn't need to manage dynamic memory, which can make it more efficient in some cases.
However, the lack of flexibility in size means that std::array
is not suitable for all situations. If you need a container that can grow or shrink as needed, std::vector
is usually the better choice.
Answers to questions are automatically generated and may not have been reviewed.
std::array
An introduction to static arrays using std::array
- an object that can store a collection of other objects