Skip to content

Module 8 · The Standard Template Library — topic 1 of 7

STL Overview

The STL is built from containers that hold data, iterators that walk through it and algorithms that process it. Learn how the three fit together and how to choose a container.

Beginner 12 min read·Lesson 31 of 40 in C++ Programming

Learning objectives

  • Name the main container families
  • Explain how iterators connect containers and algorithms
  • Choose a container from its complexity guarantees

Definition

The Standard Template Library is the part of the C++ standard library consisting of generic containers, iterators, algorithms and function objects, designed so that any algorithm can work with any container through iterators.

Introduction

Before the STL every programmer wrote their own linked lists, sorting routines and hash tables. Alexander Stepanov's STL, standardised in 1998, separated data structures from algorithms: std::sort works on any random-access range, std::find on any range at all.

Why it matters

Using the STL is faster to write, faster to run and less buggy than hand-rolled code.

Competitive programming and interviews assume fluency with vector, map, set, stack, queue and sort.

Detailed explanation

Sequence containers: vector, deque, list, forward_list, array. Associative (sorted, tree-based): set, map, multiset, multimap. Unordered (hash tables): unordered_set, unordered_map. Adaptors: stack, queue, priority_queue.

Iterators are generalised pointers: begin() points at the first element, end() one past the last. Algorithms take a pair [first, last).

Algorithms in <algorithm> and <numeric>: sort, find, count, accumulate, transform, reverse, unique, binary_search, max_element…

NeedContainerKey operation cost
Indexing, appendvectorO(1) access, amortised O(1) push_back
Insert/erase in middle with iteratorslistO(1)
Sorted unique keysset / mapO(log n)
Fast lookup by keyunordered_mapO(1) average
LIFO / FIFOstack / queueO(1)
Always get the maxpriority_queueO(log n) push/pop

Syntax

C++
#include <algorithm>
#include <numeric>
#include <vector>
std::vector<int> v{5, 2, 8};
std::sort(v.begin(), v.end());
auto it = std::find(v.begin(), v.end(), 8);
int total = std::accumulate(v.begin(), v.end(), 0);
  • Ranges are half-open: [begin, end).
  • end() must never be dereferenced.
  • Most algorithms don't change container size.

Code examples

Containers + algorithms

C++
#include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>
int main() {
std::vector<int> v{42, 7, 19, 3, 25};
std::sort(v.begin(), v.end());
int sum = std::accumulate(v.begin(), v.end(), 0);
auto big = std::count_if(v.begin(), v.end(), [](int x) { return x > 10; });
for (int x : v) std::cout << x << ' ';
std::cout << "| sum " << sum << " | >10: " << big << '\n';
return 0;
}
Output
3 7 19 25 42 | sum 96 | >10: 3

One algorithm, different containers

C++
#include <algorithm>
#include <iostream>
#include <list>
#include <string>
#include <vector>
int main() {
std::vector<std::string> v{"c", "cpp", "java"};
std::list<int> l{4, 8, 15};
std::cout << (std::find(v.begin(), v.end(), "cpp") != v.end()) << ' ';
std::cout << (std::find(l.begin(), l.end(), 16) != l.end()) << '\n';
return 0;
}
Output
1 0

More examples

Choosing containers for a word index

C++
#include <iostream>
#include <map>
#include <set>
#include <sstream>
#include <string>
#include <vector>
int main() {
std::vector<std::string> lines{"the cat sat", "the dog ran", "a cat ran"};
std::map<std::string, std::set<int>> index; // word -> sorted line numbers
for (std::size_t i = 0; i < lines.size(); ++i) {
std::istringstream ss(lines[i]);
std::string w;
while (ss >> w) index[w].insert(static_cast<int>(i + 1));
}
for (const auto& [word, where] : index) {
std::cout << word << ':';
for (int n : where) std::cout << ' ' << n;
std::cout << '\n';
}
return 0;
}
Output
a: 3
cat: 1 3
dog: 2
ran: 2 3
sat: 1
the: 1 2

Step-by-step explanation

  • A map keeps words sorted; each value is a set of line numbers (sorted, no duplicates).
  • index[w] creates an empty set the first time a word appears.
  • insert ignores duplicates automatically.
  • Structured bindings unpack each key/value pair.

Expected output

Running “Choosing containers for a word index” prints exactly:

TextOutput
a: 3
cat: 1 3
dog: 2
ran: 2 3
sat: 1
the: 1 2

Practical applications

  • Search engines build inverted indexes like this one.
  • Compilers keep symbol tables in maps.
  • Schedulers use priority queues.

Best practices

  • Start with vector; switch only for a measured reason.
  • Prefer algorithms over hand-written loops.
  • Learn the complexity of each container operation.

Common mistakes

Dereferencing end()

Avoid

auto it = std::find(v.begin(), v.end(), 99);
std::cout << *it;

Prefer

auto it = std::find(v.begin(), v.end(), 99);
if (it != v.end()) std::cout << *it;

When nothing is found, find returns end(), which doesn't refer to an element.

Using list for random access

Avoid

std::list<int> l(1000);
for (int i = 0; i < 1000; ++i) l[i]; // no operator[]

Prefer

std::vector<int> v(1000);
for (int i = 0; i < 1000; ++i) v[i];

Lists don't support indexing; use vector when you need random access.

Important notes

  • C++20 ranges let you write std::ranges::sort(v) without begin/end.
  • Iterators can be invalidated by insertions and deletions; each container documents when.

Key takeaways

  • Containers store, iterators traverse, algorithms process.
  • Ranges are half-open [begin, end).
  • Pick containers by the operations you need.

Try it yourself

  1. 1
    Read words until end of input and print each distinct word with its count, alphabetically.
  2. 2
    Use std::max_element and std::min_element on a vector of marks.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

4 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat do the iterators returned by `begin()` and `end()` denote?
  • BeginnerWhat is printed?
  • ModerateWhy does std::sort not work on a std::list?
Practise this topic