All lessons

Vectors

8 min · C++

std::vector, C++'s resizable array.

C++ · Vectors0/5 cleared

Enemy 1 of 5

What a vector is

A plain C-style array in C++ has a fixed size chosen when it's created and can't grow. std::vector<T> (from the <vector> header) solves that: it's a resizable, ordered collection of values, all of the same type T, that can grow or shrink at runtime while managing its own memory behind the scenes.

The <T> part is a template parameter. It tells the compiler exactly what type of thing the vector holds, such as vector<int> for whole numbers or vector<string> for text. This means the compiler can catch mistakes like accidentally putting a string into a vector<int> before your program ever runs.

Just like arrays and most collections in C++, vectors are indexed starting at 0, not 1. fruits[0] is the first element, fruits[1] is the second, and so on. Reading fruits[fruits.size()] or beyond is a common bug that reads past the end of the vector.

You
Bug Slime

Loading editor...

Ln 1, Col 1Spaces: 4
Sign up to fightTarget output: apple