Tutorials / C++: From Basics to Modern C++ / The STL: containers and iterators

The STL: containers and iterators

17 min read cpp
Course contents (20 lessons)
  1. Getting started
  2. Setting up a C++ compiler and writing your first program
  3. Variables, types and reading input
  4. Control flow, functions and indirection
  5. Control flow: if, switch and loops
  6. Functions: parameters, return values and overloading
  7. References and pointers
  8. Working with data
  9. Arrays and std::vector
  10. Working with std::string and string_view
  11. Classes and object-oriented design
  12. Structs and classes: your own types
  13. Constructors, destructors and RAII
  14. Operator overloading
  15. Inheritance and virtual functions
  16. Generic code and the STL
  17. Templates: writing generic code
  18. The STL: containers and iterators
  19. Algorithms and lambdas
  20. Ownership, moves and errors
  21. Smart pointers and ownership
  22. Move semantics and perfect forwarding basics
  23. Error handling: exceptions, optional and expected
  24. Modern C++ and a real project
  25. Modern C++: ranges, concepts and std::format
  26. Building projects with CMake
  27. Final project: a command-line expense tracker

What the STL is

The Standard Template Library is the part of the C++ standard library built from three ideas: containers that hold data, algorithms that work on data, and iterators that connect the two. You have already used std::vector. This lesson widens the toolbox and shows how to pick from it.

Choosing a container

ContainerWhat it isUse it when
std::vectorResizable arrayYour default. Fast to loop over, cheap to index.
std::arrayFixed-size arraySize known at compile time.
std::dequeDouble-ended queueFast add and remove at both ends.
std::listDoubly linked listRarely. Only when you need stable iterators and constant-time splicing.
std::mapSorted key-value pairsYou need keys in order, or range queries.
std::unordered_mapHash table of key-value pairsFast lookup by key, order not needed.
std::set / std::unordered_setUnique valuesMembership tests, removing duplicates.

My honest advice: start with vector. Move to a map or set when you find yourself searching by value repeatedly. Linked lists look attractive in textbooks, but modern CPUs love contiguous memory, and a vector usually beats a list even for inserts in the middle until the data gets very large. Measure if it matters.

Maps in practice

A map stores key-value pairs. A word counter is the classic use.

#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <unordered_map>

int main() {
    std::string text{"the cat saw the dog and the cat ran"};
    std::unordered_map<std::string, int> counts;

    std::istringstream in{text};
    std::string word;
    while (in >> word) {
        ++counts[word];            // creates the entry with 0 if missing
    }

    std::map<std::string, int> sorted(counts.begin(), counts.end());
    for (const auto& [w, n] : sorted) {
        std::cout << w << ": " << n << "\n";
    }
}

That prints the words in alphabetical order, with "the" counted three times. Two details worth noting. The square-bracket operator inserts a default value if the key is absent, so use it when you want that. To check for a key without inserting, use find or contains (C++20). And in the loop const auto& [w, n] is a structured binding that unpacks each key-value pair.

std::map<std::string, int> stock{{"pens", 12}, {"books", 4}};

if (stock.contains("pens")) {                 // C++20
    std::cout << stock.at("pens") << "\n";    // at() throws if the key is missing
}
stock.erase("books");
stock.insert_or_assign("ink", 7);

Sets

A set holds each value once. It is the quickest way to remove duplicates or check "have I seen this before?".

#include <set>
#include <vector>

std::vector<int> raw{4, 2, 4, 9, 2, 7};
std::set<int> unique(raw.begin(), raw.end());     // 2 4 7 9, sorted
std::cout << unique.size() << "\n";               // 4
std::cout << unique.count(7) << "\n";             // 1 (present)

Iterators

An iterator is an object that points at an element and can move to the next one. Think of it as a generalised pointer. Every container provides begin(), which points at the first element, and end(), which points one past the last. The range is half-open: it includes begin() and excludes end().

std::vector<int> v{10, 20, 30};

for (auto it = v.begin(); it != v.end(); ++it) {
    std::cout << *it << " ";       // dereference to read the element
}
std::cout << "\n";

auto found = std::find(v.begin(), v.end(), 20);   // needs <algorithm>
if (found != v.end()) {
    std::cout << "found at index " << (found - v.begin()) << "\n";   // 1
}

This explains the range-based for loop: it is shorthand for walking from begin() to end(). Dereferencing end() is an error, so always compare a search result against end() before using it.

Iterator categories

Not all iterators can do the same things. A vector iterator can jump: it + 5 is allowed. A std::list iterator can only step one at a time, forward and back. A map iterator likewise. Algorithms state which kind they need. For example, std::sort needs random access, which is why you cannot sort a std::list with it and must call list.sort() instead.

Iterator invalidation

This is the topic that separates people who have been burned from people who have not. Some operations make existing iterators invalid. For a vector, anything that causes reallocation, such as push_back beyond capacity, invalidates all of them. erase invalidates iterators at and after the erased position. Using an invalid iterator is undefined behaviour.

The safe way to erase while looping uses the iterator that erase returns.

for (auto it = v.begin(); it != v.end(); ) {
    if (*it % 20 == 0) {
        it = v.erase(it);       // returns the next valid iterator
    } else {
        ++it;
    }
}

Notice the loop has no ++it in the header. We only advance when we did not erase. In C++20 you can replace the whole loop with std::erase_if(v, [](int x) { return x % 20 == 0; });.

The common mistake

Using a map's operator[] to check whether a key exists. It inserts the key, so after the check, the key exists. Another one: keeping an iterator or reference into a vector across a push_back. And choosing std::list because "inserting is O(1)" without measuring. For most programs a vector is both simpler and faster.

Try it yourself

  1. Read a text file with std::ifstream and print the five most common words. Hint: count in a map, copy to a vector of pairs, sort by count.
  2. Use a std::set to print the unique characters in a string, in sorted order.
  3. Write a loop that removes all even numbers from a vector using iterators and erase. Then redo it with std::erase_if.
cpp
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <unordered_map>

int main() {
    std::string text{"the cat saw the dog and the cat ran"};
    std::unordered_map<std::string, int> counts;

    std::istringstream in{text};
    std::string word;
    while (in >> word) {
        ++counts[word];            // creates the entry with 0 if missing
    }

    std::map<std::string, int> sorted(counts.begin(), counts.end());
    for (const auto& [w, n] : sorted) {
        std::cout << w << ": " << n << "\n";
    }
}

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account