Lesson 21 — The Standard Library

The Standard Template Library (STL)

The STL is a collection of ready-made, well-tested generic containers and algorithms that ship with every standard C++ compiler, saving you from reinventing common data structures.

std::vector — A Dynamic Array

Unlike a plain array, std::vector can grow and shrink at runtime, and it tracks its own size. It is the default choice for an ordered, resizable collection in modern C++.

C++ — std::vector
#include <vector>
#include <algorithm>

std::vector<int> scores = {88, 92, 79};
scores.push_back(100);           // add an element
scores.pop_back();                // remove the last element

for (int s : scores) {
    std::cout << s << " ";
}

std::sort(scores.begin(), scores.end()); // sort ascending

std::map — Key/Value Pairs

A std::map stores key-value pairs, automatically kept sorted by key, and gives you fast lookup by key instead of by numeric position.

C++ — std::map
#include <map>

std::map<std::string, int> ages;
ages["Sipho"] = 22;
ages["Zanele"] = 25;

for (auto &pair : ages) {
    std::cout << pair.first << " is " << pair.second << std::endl;
}

Common Mistakes

  • Using a plain array instead of a std::vector when the size of a collection isn't known in advance.
  • Accessing a vector with [] out of bounds — unlike .at(), [] does not check bounds and causes undefined behaviour.
  • Forgetting to #include <algorithm> before using functions like std::sort or std::find.
  • Assuming a std::map preserves insertion order — it actually keeps entries sorted by key.

Professional Tip

Use .at(index) instead of [index] on a vector while debugging — it throws a catchable std::out_of_range exception on an invalid index instead of silently corrupting memory.

Your Turn

Create a std::vector of ten integers entered by the user, then use std::sort to sort them and std::find to check whether a specific value the user enters exists in the vector.

Mini Quiz

What is the main advantage of std::vector over a plain fixed-size array?