Knowledge / Computer Applications / C++ Standard Template Library (STL) for problem solving

C++ Standard Template Library (STL) for problem solving

Computer Applications (MCA) · Programming and data structures · free study notes for exams, placements and interviews

In short

The Standard Template Library is the part of the C++ standard library that provides ready-made generic containers (vector, map, set, deque), iterators that walk over them, and algorithms (sort, lower_bound, next_permutation) that work on any container through those iterators. It is built on templates, so one sort works for int, string or a user-defined struct, and every operation carries a documented complexity guarantee. For placement coding rounds — Amazon, Microsoft, Google, Flipkart, Zoho, Walmart, Oracle, Goldman Sachs, Samsung R&D, service companies' advanced tracks, and platforms such as CodeChef, HackerRank, HackerEarth and Codeforces — STL fluency is the difference between a 10-line accepted solution and a 100-line buggy one. University MCA papers and lab vivas ask for container definitions, complexities, iterator categories and small programs; GATE tests the underlying data-structure complexities that the STL implements.

Explained

What the STL is: six components

Sequence containers

Ordered associative containers (balanced BST, usually red-black tree)

Unordered containers (hash table with separate chaining)

Container adaptors

Iterators

Algorithms and the problem-solving toolkit

Choosing the right container — the decision that is actually marked

  1. Need indexing and mostly appends → vector.
  2. Need both ends → deque; only one end LIFO/FIFO → stack/queue.
  3. Need fastest key lookup, order irrelevant → unordered_map/set.
  4. Need sorted order, predecessor/successor, range queries → map/set.
  5. Need repeated "extract minimum/maximum" → priority_queue (or multiset if arbitrary deletion is also needed).
  6. Need many insert/erase at known positions with stable iterators → list.
  7. Constant factors matter: vector beats list in practice even for mid-insertions at small n because of cache locality; unordered_map beats map typically 3–10× but loses ordering.

Key points

Formulas and examples

Amortised cost of n push_back calls with growth factor 2 = O(n); total element copies < 2n starting from capacity 1 (exactly n − 1 when n is a power of two)
Reallocations for n push_backs from capacity 1 = ⌈log₂ n⌉ + 1 (capacities 1, 2, 4, …)
sort: T(n) = O(n log₂ n) comparisons; memory O(log n). stable_sort: O(n log n) with O(n) extra memory
map/set operation cost = O(log₂ n); n operations = O(n log₂ n). unordered_map average O(1), worst O(n)
Load factor α = number of elements / bucket_count; rehash occurs when α > max_load_factor (default 1.0)
Frequency of x in sorted range = upper_bound(x) − lower_bound(x); number of elements in [L, R] = upper_bound(R) − lower_bound(L)
priority_queue: push/pop O(log₂ n), top O(1); make_heap O(n); heap-sort of n items O(n log₂ n)
Permutations generated by repeated next_permutation from the sorted sequence = n!

Example 1 — vector growth cost. Push 1,000 ints into an empty vector<int> whose capacity starts at 1 and doubles.

Example 2 — container choice by operation count. 2 × 10⁵ insertions plus 2 × 10⁵ lookups.

Example 3 — binary search bounds. Sorted array a = 2, 4, 4, 4, 7, 9, 11 (0-based).

Example 4 — dedupe and coordinate compression.

vector<int> a = {3, 1, 3, 2, 1, 7};
sort(a.begin(), a.end());                       // 1 1 2 3 3 7
a.erase(unique(a.begin(), a.end()), a.end());   // 1 2 3 7  -> size 4
int id = lower_bound(a.begin(), a.end(), 3) - a.begin();   // id = 2

Example 5 — top-3 of 10⁶ numbers.

Example 6 — k-th largest with a min-heap. Stream of 10⁶ values, k = 100: keep a priority_queue<int, vector<int>, greater<int>> of size 100; per element cost log₂100 ≈ 6.64, total ≈ 6.6 × 10⁶ operations and only 100 ints of memory, versus 4 MB to store all values.

ContainerUnderlying structureFindInsertEraseIndexOrdered
vectordynamic arrayO(n)O(1) amortised at end, O(n) middleO(n)O(1)insertion order
dequeblocksO(n)O(1) both endsO(1) endsO(1)insertion order
listdoubly linkedO(n)O(1) with iteratorO(1) with iteratornoinsertion order
set / mapred-black treeO(log n)O(log n)O(log n)noyes (sorted)
unordered_set / maphash tableO(1) avg, O(n) worstO(1) avgO(1) avgnono
priority_queuebinary heaptop only O(1)O(log n)O(log n) pop topnopartial
bitset<N>bit arrayO(1)fixed sizefixed sizeO(1)positional
NeedUseWhy not the other
Count word frequencies, print alphabeticallymap<string,int>unordered_map needs an extra sort
Visited marks for 10⁶ integer IDsvector<bool> or bitsethash set wastes time and memory
Next bus after time tset/map lower_boundunordered has no ordering
Sliding-window maximumdeque of indicesmultiset works but is O(n log n)
Merge k sorted listspriority_queue of (value, list id)sorting everything loses the k log factor

Where it is used

Interview questions

Common mistakes

Related topics

Arrays and strings · Linked lists · Trees and binary search trees · Hashing and hash tables · Time and space complexity · DSA interview patterns

Open in the Knowledge reader →Find jobs →