Skip to content

Module 4 · Pointers, Arrays, Strings and Structures — topic 2 of 4

Arrays, std::array and std::vector

Built-in arrays, the fixed-size std::array and the resizable std::vector: declaration, access, size, passing to functions and choosing the right one.

Beginner 15 min read·Lesson 14 of 40 in C++ Programming

Learning objectives

  • Use built-in arrays, std::array and std::vector
  • Explain size(), push_back, at() and bounds checking
  • Choose the right container for a task

Definition

A built-in array is a fixed-size contiguous sequence of elements. std::array<T, N> wraps it with a size and value semantics; std::vector<T> is a dynamically resizable contiguous array that manages its own memory.

Introduction

C++ inherits C arrays, with all their problems: they don't know their own size, decay to pointers, and can't be copied or returned. The standard library offers two better options: std::array for fixed sizes and std::vector when the size changes.

Why it matters

std::vector is the default container in C++ and appears in almost every program and project.

Using std::array/std::vector removes the decay and size-tracking bugs of C arrays.

Detailed explanation

int a[5]{}; is a built-in array; std::size(a) (C++17) gives 5.

std::array<int, 5> b{}; has b.size(), can be copied with =, compared with == and returned from functions.

std::vector<int> v; starts empty; push_back appends; size() counts; resize and reserve manage capacity. Memory is freed automatically.

v[i] is unchecked (out of range is undefined behaviour); v.at(i) throws std::out_of_range when i is invalid.

T[N]std::array<T,N>std::vector<T>
Size fixed?yesyesno
Knows its sizeonly in scopesize()size()
Copy with =noyesyes
Memorystack/staticstack/staticheap
Pass to functiondecays to pointerby referenceby reference

Syntax

C++
int raw[3] = {1, 2, 3};
std::array<int, 3> fixed{1, 2, 3};
std::vector<int> grow{1, 2, 3};
grow.push_back(4);
int x = grow.at(2); // bounds-checked
void process(const std::vector<int>& v);
  • Include <array> and <vector>.
  • Pass vectors by (const) reference.
  • Prefer range-for or algorithms to index loops.

Code examples

std::vector basics

C++
#include <iostream>
#include <vector>
int main() {
std::vector<int> marks;
for (int m : {72, 88, 95}) marks.push_back(m);
marks[0] = 75;
std::cout << marks.size() << ' ' << marks.front() << ' ' << marks.back() << '\n';
return 0;
}
Output
3 75 95

std::array copies and compares

C++
#include <array>
#include <iostream>
int main() {
std::array<int, 3> a{1, 2, 3};
std::array<int, 3> b = a; // full copy
b[0] = 9;
std::cout << a[0] << ' ' << b[0] << ' ' << (a == b) << ' ' << a.size() << '\n';
return 0;
}
Output
1 9 0 3

More examples

Bounds checking and capacity

C++
#include <iostream>
#include <stdexcept>
#include <vector>
int main() {
std::vector<int> v;
v.reserve(4);
for (int i = 1; i <= 4; ++i) v.push_back(i * 10);
std::cout << "size " << v.size() << ", capacity >= 4: " << (v.capacity() >= 4) << '\n';
try {
std::cout << v.at(10) << '\n';
} catch (const std::out_of_range& e) {
std::cout << "caught out_of_range\n";
}
v.erase(v.begin() + 1); // remove 20
v.insert(v.begin(), 5); // add 5 at the front
for (int x : v) std::cout << x << ' ';
std::cout << '\n';
return 0;
}
Output
size 4, capacity >= 4: 1
caught out_of_range
5 10 30 40

Step-by-step explanation

  • reserve(4) allocates room for four elements up front.
  • at(10) is out of range and throws instead of reading random memory.
  • erase removes the element at position 1 (20), shifting the rest.
  • insert at begin() shifts everything right.

Expected output

Running “Bounds checking and capacity” prints exactly:

TextOutput
size 4, capacity >= 4: 1
caught out_of_range
5 10 30 40

Practical applications

  • Game engines store entities in vectors for cache-friendly iteration.
  • std::array holds fixed-size data such as RGB colours or 3D coordinates.
  • Competitive programmers use vectors for nearly every array.

Best practices

  • Default to std::vector.
  • Use std::array for small, fixed sizes.
  • Use at() while debugging or for untrusted indexes.

Common mistakes

Indexing an empty vector

Avoid

std::vector<int> v;
v[0] = 5;

Prefer

std::vector<int> v;
v.push_back(5);

An empty vector has no element 0; v[0] is undefined behaviour.

Passing a vector by value

Avoid

int sum(std::vector<int> v);

Prefer

int sum(const std::vector<int>& v);

By value copies every element on each call.

Important notes

  • push_back may reallocate, invalidating pointers, references and iterators to elements.
  • std::vector<bool> is a special bit-packed specialisation that does not behave exactly like other vectors.

Key takeaways

  • Prefer std::vector / std::array to built-in arrays.
  • at() is bounds-checked; [] is not.
  • Pass containers by const reference.

Try it yourself

  1. 1
    Read numbers until end of input into a vector and print them in reverse.
  2. 2
    Remove all even numbers from a vector using erase in a loop (or std::erase_if in C++20).

Finished reading? Mark it complete to update your dashboard.

Suggested practice

5 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
  • BeginnerWhat happens with `v.at(10)` on a vector of size 3?
  • BeginnerWhich is a key advantage of std::array<int, 5> over int[5]?
Practise this topic