Odds and Ends: 10 Useful Techniques

When to use std::vector vs std::array

When should I use std::vector and when should I use std::array in C++?

Abstract art representing computer programming

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.

Answers to questions are automatically generated and may not have been reviewed.

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