The Standard Template Library
The STL is the heart of modern C++ programming. It provides a rich set of containers, algorithms, and utilities that enable efficient and expressive code.
Containers
Sequence Containers
#include <vector>
#include <array>
#include <deque>
#include <list>
// std::vector - dynamic array
std::vector<int> vec = {1, 2, 3, 4, 5};
vec.push_back(6);
vec.emplace_back(7); // construct in-place
// std::array - fixed-size array
std::array<int, 5> arr = {1, 2, 3, 4, 5};
// std::deque - double-ended queue
std::deque<int> dq;
dq.push_front(1);
dq.push_back(2);
Associative Containers
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
// std::map - ordered key-value pairs
std::map<std::string, int> ages;
ages["Alice"] = 30;
ages.insert({"Bob", 25});
// std::unordered_map - hash-based (faster lookup)
std::unordered_map<std::string, int> fast_ages;
fast_ages["Charlie"] = 35;
// std::set - ordered unique elements
std::set<int> unique_numbers = {3, 1, 4, 1, 5, 9}; // {1, 3, 4, 5, 9}
Algorithms
The <algorithm> header provides 100+ algorithms:
Searching and Sorting
#include <algorithm>
std::vector<int> v = {5, 2, 8, 1, 9, 3};
// Sorting
std::sort(v.begin(), v.end()); // {1, 2, 3, 5, 8, 9}
std::sort(v.begin(), v.end(), std::greater<int>()); // descending
// Binary search (requires sorted range)
bool found = std::binary_search(v.begin(), v.end(), 5);
auto it = std::lower_bound(v.begin(), v.end(), 5);
// Finding
auto pos = std::find(v.begin(), v.end(), 8);
auto pos2 = std::find_if(v.begin(), v.end(), [](int n) { return n > 5; });
Transforming
std::vector<int> src = {1, 2, 3, 4, 5};
std::vector<int> dst(5);
// Transform
std::transform(src.begin(), src.end(), dst.begin(),
[](int n) { return n * n; }); // dst: {1, 4, 9, 16, 25}
// Copy with condition
std::vector<int> evens;
std::copy_if(src.begin(), src.end(), std::back_inserter(evens),
[](int n) { return n % 2 == 0; });
// Accumulate
int sum = std::accumulate(src.begin(), src.end(), 0);
int product = std::accumulate(src.begin(), src.end(), 1, std::multiplies<int>());
Modifying
std::vector<int> v = {1, 2, 2, 3, 3, 3, 4};
// Remove duplicates (from sorted range)
auto last = std::unique(v.begin(), v.end());
v.erase(last, v.end()); // {1, 2, 3, 4}
// Replace
std::replace(v.begin(), v.end(), 3, 30);
// Rotate
std::rotate(v.begin(), v.begin() + 2, v.end());
// Shuffle
std::random_device rd;
std::mt19937 gen(rd());
std::shuffle(v.begin(), v.end(), gen);
Iterators
- Input iterators: Read-only, single-pass
- Output iterators: Write-only, single-pass
- Forward iterators: Read/write, multi-pass
- Bidirectional iterators: Can move backwards
- Random access iterators: Direct element access