TeachMate
My ProgressJoin Session

Standard Template Library

0/7 completed · ~0h 25m

All Topics
C++LearnStandard Template Library
1 / 7

STL

intermediate
2 min read

The Standard Template Library (STL) provides ready-to-use data structures and algorithms. It is one of C++'s greatest strengths — you don't need to implement common data structures from scratch.

Why STL Matters

  • Battle-tested, optimized implementations
  • Generic programming — works with any data type
  • Reduces bugs by avoiding manual memory management
  • Standard across all C++ compilers and platforms

STL Components

  1. Containers: store data (vector, map, set, etc.)
  2. Algorithms: operate on containers (sort, find, etc.)
  3. Iterators: traverse containers

Vector (Dynamic Array)

Vector is the default STL container. It is introduced in the Arrays & Strings topic; here we only note that it is a sequence container that grows dynamically and works with the algorithms below.

Algorithms

#include <algorithm>
sort(v.begin(), v.end());        // Sort ascending
sort(v.begin(), v.end(), greater<int>());  // Sort descending
reverse(v.begin(), v.end());     // Reverse
auto it = find(v.begin(), v.end(), 8);  // Find element
int count = std::count(v.begin(), v.end(), 5);  // Count

Other Containers

  • deque: double-ended queue
  • list: doubly-linked list
  • set: sorted unique elements
  • map: sorted key-value pairs
  • unordered_map: hash map (faster lookup)
  • stack: LIFO
  • queue: FIFO
  • priority_queue: priority-based queue

Common mistakes: using v[i] without bounds checking (v.at(i) checks) and modifying a vector while an iterator points into it, which invalidates that iterator.

Key takeaway: STL provides containers, algorithms, and iterators — use vector as your default container.

Try it: Create a vector<int>, sort it, print the smallest element with front(), and count how many times a chosen value appears.

TeachMate - Interactive learning platform for bachelor students

HomeLearnJoin Session|2 Subjects