Static Arrays using std::array

Changing Array Size

Can I change the size of a std::array after it has been created?

Abstract art representing computer programming

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.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved