Skip to content
  • STL Overview · C++

STL Overview

LearnViaNotes @learnvianotes· 2 min read

The Standard Template Library is three ideas that plug together: containers hold data, iterators walk it, algorithms process it — all generic, all zero-overhead.

Container → Iterators begin()/end() → Algorithm

C++
#include <algorithm>
#include <iostream>
#include <list>
#include <vector>

int main() {
    std::vector<int> v{4, 1, 3};
    std::list<int> l{4, 1, 3};
    // The same algorithm works on any container through iterators:
    std::cout << *std::max_element(v.begin(), v.end()) << ' '
              << *std::max_element(l.begin(), l.end()) << '\n';
    std::cout << std::count(v.begin(), v.end(), 3) << '\n';
}
Output
4 4
1

Container families

FamilyContainersOrganised by
Sequencevector, deque, list, forward_list, arrayPosition (the order you insert)
Ordered associativeset, multiset, map, multimapSorted keys (red-black tree)
Unordered associativeunordered_set/_multiset, unordered_map/_multimapHash of the key
Adaptorsstack, queue, priority_queueA restricted interface over another container
Views (non-owning)string_view, span, ranges viewsRefer to someone else's data

Complexity cheat sheet

ContainerAccessSearchInsert/erase at endInsert/erase in middle / front
vectorO(1) randomO(n)O(1) amortisedO(n)
dequeO(1) randomO(n)O(1)O(1) at front, O(n) middle
listO(n)O(n)O(1)O(1) given an iterator
set / map—O(log n)O(log n)O(log n)
unordered_set / unordered_map—O(1) avg, O(n) worstO(1) avgO(1) avg
priority_queueO(1) top—push/pop O(log n)—

Choosing a container

  1. Default

    std::vector — contiguous, cache-friendly, fastest for most workloads, even with some middle inserts.

  2. Need lookup by key?

    std::unordered_map/unordered_set for speed; std::map/set when you need sorted order or range queries (lower_bound).

  3. Push/pop at both ends?

    std::deque.

  4. LIFO / FIFO / “always give me the max”?

    std::stack / std::queue / std::priority_queue.

  5. Many inserts/erases in the middle with stable iterators?

    std::list — rarely the right answer in practice.

Why is std::vector usually faster than std::list even for insertions?

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report