C++ ยท Chapter 43 of 49

C++ STL Vectors

`std::vector<T>` is a dynamic array from the Standard Template Library that automatically grows and shrinks as you add or remove elements. It's the default go-to container for most C++ programs and competitive programming solutions.

Common operations include `.push_back()` to add an element, `.size()` to get the count, `.pop_back()` to remove the last element, and `[]` or `.at()` for indexed access.

Creating and modifying vectors

`std::vector<int> v;` starts empty; `v.push_back(5);` adds 5 to the end. `v.size()` tells you how many elements are currently stored.

Iterating a vector

Use a range-based for loop `for (int x : v)` or index-based `for (int i = 0; i < v.size(); i++)` to visit every element.

Example 1 (cpp)
#include <vector>
std::vector<int> v;
v.push_back(1);
v.push_back(2);
std::cout << v.size() << " " << v[0];
Output
2 1

push_back adds elements; size() and [] inspect the vector.

Example 2 (cpp)
std::vector<int> v = {5, 10, 15};
for (int x : v) std::cout << x << " ";
Output
5 10 15 

Range-based for loops over every vector element.

Key points

  • std::vector is a dynamic, resizable array (needs #include <vector>).
  • push_back() appends; pop_back() removes the last element.
  • size() returns the current element count.
  • Vectors support [] indexing like arrays.
๐Ÿ’ก Note: Vectors may reallocate memory when they grow, invalidating existing iterators/pointers โ€” be careful when modifying while iterating.

๐Ÿ“ Quick Quiz

1. Which method adds an element to the end of a vector?

2. Which header defines std::vector?

3. What does v.size() return?