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

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Measuring execution time with
How can I measure the execution time of a function using the library?
Choosing the right random number distribution
How do I choose the appropriate random number distribution for my use case?
Using [[nodiscard]] with custom types
How can I use the [[nodiscard]] attribute with my own custom types?
Creating a custom ClangFormat style
How can I create a custom ClangFormat style for my C++ project?
Integrating static analysis tools into your workflow
How can I integrate static analysis tools like Cppcheck into my C++ development workflow?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant