STL Overview
The four components of the STL
Component | Purpose | Examples |
|---|---|---|
Containers | Store and organize collections of objects | vector, list, deque, set, map, unordered_map, stack, queue |
Algorithms | Operate on ranges of elements via iterators | sort, find, count, accumulate, transform, copy |
Iterators | A uniform way to traverse any container | begin()/end(), forward/bidirectional/random-access iterators |
Function objects (functors) | Encapsulate an operation as an object; customize algorithm behavior | std::less, std::greater, lambdas passed to algorithms |
Why iterators matter
stl_glue.cpp
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> numbers = {5, 3, 8, 1, 9, 2};
// std::sort doesn't know anything about "vector" specifically —
// it only needs a begin/end iterator pair.
std::sort(numbers.begin(), numbers.end());
for (int n : numbers) {
std::cout << n << " ";
}
std::cout << std::endl; // 1 2 3 5 8 9
auto it = std::find(numbers.begin(), numbers.end(), 8);
if (it != numbers.end()) {
std::cout << "Found 8!" << std::endl;
}
return 0;
}Why prefer the STL over hand-rolled code
STL containers and algorithms are written and tuned by compiler and library implementers, and are far more likely to be correct and efficient than a quick hand-rolled linked list or bubble sort.
They are extensively tested and used by essentially every C++ program in existence — bugs are rare and well understood.
Code that uses
std::vectorandstd::sortcommunicates intent clearly to other C++ programmers; a hand-rolled dynamic array does not.The STL is part of the standard — no external dependency required, and it works the same way across compilers and platforms.