STL Containers & Algorithms
The Standard Template Library (STL) provides production-ready containers (vector, map, set), algorithms (sort, find, transform), and iterators. Master the STL to write efficient, clean C++ without reinventing data structures.
45 min•By Priygop Team•Last updated: Feb 2026
STL Code
Example
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <algorithm>
#include <numeric>
using namespace std;
int main() {
// vector (dynamic array)
vector<int> nums = {5, 2, 8, 1, 9, 3};
nums.push_back(7);
nums.emplace_back(4); // Construct in-place (faster)
// STL algorithms
sort(nums.begin(), nums.end());
auto it = find(nums.begin(), nums.end(), 8);
if (it != nums.end()) cout << "Found 8 at index " << (it - nums.begin()) << endl;
int total = accumulate(nums.begin(), nums.end(), 0);
cout << "Sum: " << total << endl;
// transform: apply function to each element
vector<int> doubled(nums.size());
transform(nums.begin(), nums.end(), doubled.begin(), [](int n) { return n * 2; });
// map (ordered key-value pairs, O(log n))
map<string, int> ages = {{"Alice", 30}, {"Bob", 25}};
ages["Charlie"] = 35;
ages.insert({"Diana", 28});
for (const auto &[name, age] : ages) { // Structured bindings (C++17)
cout << name << ": " << age << endl;
}
// unordered_map (hash table, O(1) average)
// #include <unordered_map>
// Same API as map but faster for lookups
// set (unique sorted elements)
set<int> unique = {3, 1, 4, 1, 5, 9, 2, 6, 5};
// Contains: {1, 2, 3, 4, 5, 6, 9} — duplicates removed, sorted
// Check existence
if (unique.count(4)) cout << "4 exists" << endl;
if (unique.contains(4)) cout << "4 exists (C++20)" << endl;
return 0;
}