The Runtime Theory
C++

STL Containers and Algorithms

std::vector, std::map, std::unordered_map, std::set, iterators, and the algorithm functions that operate on them.

The Runtime Theory Team1 min read
▸ On this page

STL Containers and Algorithms

The Standard Template Library (STL) provides containers and algorithms that are the backbone of C++ programming.

Containers

Sequential Containers

ContainerAccessInsert/Remove (end)Insert/Remove (middle)Memory
std::vectorO(1) randomO(1) amortizedO(n)Contiguous
std::arrayO(1) randomN/A (fixed)N/AContiguous
std::dequeO(1) randomO(1) amortizedO(n)Segmented
std::listO(n) linear onlyO(1) at endsO(1) with iteratorLinked

Associative Containers

ContainerLookupOrdered?Duplicates?
std::setO(log n)✅ Yes❌ No
std::mapO(log n)✅ YesKeys must be unique
std::multisetO(log n)✅ Yes✅ Yes
std::multimapO(log n)✅ Yes✅ Yes
std::unordered_setO(1) avg❌ No❌ No
std::unordered_mapO(1) avg❌ NoKeys must be unique
std::unordered_multisetO(1) avg❌ No✅ Yes
std::unordered_multimapO(1) avg❌ No✅ Yes

Adapters

AdapterUnderlyingUse
std::stackstd::deque (default)LIFO — push/pop from one end
std::queuestd::deque (default)FIFO — push to back, pop from front
std::priority_queuestd::vector (default)Max-heap — push/pop highest priority

Algorithms

The <algorithm> header provides functions that work on any iterator range:

cpp
std::vector<int> v = {5, 2, 8, 1, 9};
 
std::sort(v.begin(), v.end());           // ascending sort
std::reverse(v.begin(), v.end());        // reverse
auto it = std::find(v.begin(), v.end(), 8);  // linear search
auto count = std::count(v.begin(), v.end(), 5);  // count occurrences
auto minmax = std::minmax_element(v.begin(), v.end());  // both
auto sum = std::accumulate(v.begin(), v.end(), 0);  // sum (in <numeric>)
auto [it, ok] = std::binary_search(...);  // binary search (requires sorted)
 
// Transform one range into another
std::transform(v.begin(), v.end(), result.begin(),
  [](int x) { return x * 2; });  // lambda function

Complexity Guarantees

  • std::sort — O(n log n) average, O(n log n) worst
  • std::find — O(n) linear search
  • std::binary_search — O(log n), but requires sorted range
  • std::unordered_map::find — O(1) average, O(n) worst
  • std::map::find — O(log n) always

The STL is designed so you can swap containers without changing algorithm code — that's the power of iterators.

Not started

Sign in to save your learning progress.

Sign in to save