⚡0 XP🔥0

The Standard Template Library (STL)

Lesson 10 of 12 ⏱ 8 min read ✎ 3 exercises ❓ 5-question quiz ▶ Runs C++

Containers (vector, list, deque, stack, queue, priority_queue, set, map, unordered_map), iterators and algorithms (sort, find, count, accumulate, binary_search) with time complexities.

The Standard Template Library (STL) is C++'s toolbox of ready-made, well-tested, fast containers (data structures), iterators (ways to walk through them) and algorithms (sort, search, count...). Knowing the STL well is the single biggest speed-up for placements and competitive programming.

Containers at a glance#

Container What it is Typical use Insert / find
vector dynamic array most lists end O(1), find O(n)
deque double-ended queue add/remove at both ends ends O(1)
list doubly linked list frequent middle inserts O(1) insert given position
stack LIFO undo, brackets, DFS push/pop O(1)
queue FIFO BFS, task queues push/pop O(1)
priority_queue heap always get max (or min) O(log n)
set sorted unique values uniqueness + order O(log n)
map sorted key → value dictionaries, counting O(log n)
unordered_set / unordered_map hashed fastest lookup, no order O(1) average
हिंदी में समझें

STL मतलब पहले से बनी हुई data structures और algorithms का खज़ाना। आपको linked list, stack, queue, sorting खुद नहीं लिखने पड़ते - बस सही container चुनिए। Interview में अक्सर पूछा जाता है कि कौन सा container कब और उसका time complexity क्या है।

Iterators#

An iterator is like a pointer into a container. begin() points to the first element, end() to one-past-the-last. Algorithms take a range [begin, end):

▶ Try it YourselfC++
Ctrl + Enter to run
Output
10 20 30 40 
40 30 20 10 
20 25 30 40 

map - key/value pairs, sorted by key#

▶ Try it YourselfC++
Ctrl + Enter to run
Output
Items: 4
eraser = 80
marker = 30
notebook = 45
pen = 100
No staplers
eraser found: 80
After erase: 3 items
Common Mistake

m[key] creates the key (with value 0 / empty) if it does not exist. To only check, use m.count(key) or m.find(key).

set and unordered_map#

▶ Try it YourselfC++
Ctrl + Enter to run
Output
4 unique cities: Bhopal Dewas Indore Ujjain
Capital of MP: Bhopal
Has Goa? false

stack, queue and priority_queue#

▶ Try it YourselfC++
Ctrl + Enter to run
Output
stack pops: 3 2 1
queue serves: Asha Ravi Imran
max-heap top: 70, min-heap top: 10

Algorithms (<algorithm> and <numeric>)#

▶ Try it YourselfC++
Ctrl + Enter to run
Output
sum      = 251
max      = 88
count(7) = 2
88 at index 3
evens    = 2
sorted   : 7 7 19 25 42 63 88
has 25?  true
unique   : 7 19 25 42 63 88
reversed : 88 63 42 25 19 7

Sorting with a custom rule#

Pass a comparison (often a lambda) as the third argument of sort:

▶ Try it YourselfC++
Ctrl + Enter to run
Output
Aditi 9.47
Nisha 9.47
Kabir 9.16
Yash 7.78

pair and tuple#

pair<A, B> holds two values (first, second) - map elements are pairs. make_pair, tuple and structured bindings make returning several values easy:

▶ Try it YourselfC++
Ctrl + Enter to run
Output
Top: Riya (92)
min 1, max 15

Choosing a container - quick guide#

  • Need a list and index access? vector.
  • Need "have I seen this?" or uniqueness? set (sorted) / unordered_set (fastest).
  • Need to count or map keys to values? map (sorted output) / unordered_map (fastest).
  • Need the smallest/largest repeatedly? priority_queue.
  • Processing in arrival order? queue. Last-in-first-out? stack.

Summary#

  • Containers store data; iterators walk them; algorithms work on iterator ranges.
  • map/set are sorted trees (O(log n)); unordered_* are hash tables (O(1) average).
  • stack, queue, priority_queue adapt other containers.
  • sort, find, count, accumulate, binary_search, max_element save you from writing loops; pass lambdas for custom rules.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Word counter with map

Read words until the end of input and print each distinct word with its count, in alphabetical order (word: count).

Test input:
the cat and the dog and the bird
Expected output:
and: 2
bird: 1
cat: 1
dog: 1
the: 3
2

Remove duplicates, keep sorted

Read n numbers and print the distinct values in increasing order on one line, then Distinct: k. Use a set<int>.

Test input:
10
5 3 9 3 1 5 9 9 7 1
Expected output:
1 3 5 7 9
Distinct: 5
3

Balanced brackets with a stack

Read a line of brackets ()[]{} and print Balanced or Not balanced using stack<char>. Test input {[()()]}(].

Test input:
{[()()]}(]
Expected output:
Not balanced

Quick Quiz

Q1.

Which container keeps its keys sorted automatically?

Q2.

What is the average time to look up a key in an unordered_map?

Q3.

A set stores...

Q4.

Which container gives the largest element first?

Q5.

What does accumulate(v.begin(), v.end(), 0) compute?