The STL: containers and iterators
Course contents (20 lessons)
- Getting started
- Setting up a C++ compiler and writing your first program
- Variables, types and reading input
- Control flow, functions and indirection
- Control flow: if, switch and loops
- Functions: parameters, return values and overloading
- References and pointers
- Working with data
- Arrays and std::vector
- Working with std::string and string_view
- Classes and object-oriented design
- Structs and classes: your own types
- Constructors, destructors and RAII
- Operator overloading
- Inheritance and virtual functions
- Generic code and the STL
- Templates: writing generic code
- The STL: containers and iterators
- Algorithms and lambdas
- Ownership, moves and errors
- Smart pointers and ownership
- Move semantics and perfect forwarding basics
- Error handling: exceptions, optional and expected
- Modern C++ and a real project
- Modern C++: ranges, concepts and std::format
- Building projects with CMake
- 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
| Container | What it is | Use it when |
|---|---|---|
std::vector | Resizable array | Your default. Fast to loop over, cheap to index. |
std::array | Fixed-size array | Size known at compile time. |
std::deque | Double-ended queue | Fast add and remove at both ends. |
std::list | Doubly linked list | Rarely. Only when you need stable iterators and constant-time splicing. |
std::map | Sorted key-value pairs | You need keys in order, or range queries. |
std::unordered_map | Hash table of key-value pairs | Fast lookup by key, order not needed. |
std::set / std::unordered_set | Unique values | Membership 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
- Read a text file with
std::ifstreamand print the five most common words. Hint: count in a map, copy to a vector of pairs, sort by count. - Use a
std::setto print the unique characters in a string, in sorted order. - Write a loop that removes all even numbers from a vector using iterators and
erase. Then redo it withstd::erase_if.
#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