Lesson 86 +10 XP

std::vector

std::vector

std::vector is the standard library's dynamic container: it can grow and shrink while your program runs. It's usually the first container to reach for.

Declaring a vector

#include <vector>

std::vector<int> v = {1, 2, 3};
  • std::vector<int> - a vector holding integers.
  • = {1, 2, 3} - start it with three values.
  • Notice you never had to name a maximum size.

Adding elements with push_back

v.push_back(4);   // v is now {1, 2, 3, 4}

push_back appends an element to the back of the vector, growing it automatically. No rethinking about a size limit.

Asking for the size

#include <iostream>
std::cout << v.size() << "\n";   // 4

size() returns how many elements the vector currently holds (as a size_t). No need to track the length yourself.

TL;DR

  • #include <vector> to use it.
  • Declare with std::vector<int> v = {1, 2, 3};.
  • v.push_back(4) adds an element at the back.
  • v.size() tells you how many elements it holds.
  • A vector needs no fixed size - it grows on demand.