Vectors
8 min · C++
std::vector, C++'s resizable array.
Enemy 1 of 5
What a vector is
A vector is a list that can grow and shrink, and every item has the same type. This code makes a vector of fruit names and prints the first one. Press Run to see it.
Why this works
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.
Rena
Your AI tutor. She walks you through each step.
Asking for help is part of coding. Rena reads your code and gives you a hint. She is free with an account: 20 hints a day.