C++ STL
STL Overview
Complete lesson for STL Overview using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with C++ OOP and STL where relevant.
Basics — STL Overview
Section: C++ STL. C++ STL overview — containers, iterators, algorithms, adapters, and why the Standard Template Library saves time.
What is the STL?
- The **STL** (Standard Template Library) is a powerful set of **pre-written** template classes and functions in the C++ standard library.
- It gives you ready-to-use **data structures**, **algorithms**, and utilities.
- Built with **templates** — works with any suitable type.
- Main pieces: **containers**, **algorithms**, **iterators**, plus functors, adapters, and allocators.
- **Real-life:** a toolbox of tested tools so you build the house (your logic), not the hammer.
| Idea | Meaning |
|---|---|
| STL | Part of the C++ standard library |
| Templates | Generic code for many types |
| Containers | Store and organize data |
| Algorithms | Operate on ranges via iterators |
| Goal | Less boilerplate, fewer bugs, more speed |
STL overview — containers, iterators, algorithms
The Standard Template Library gives you ready-made data structures and algorithms. The diagram covers components, container categories, quick demos, common algorithms, iterators, adapters, advantages, and use cases.
- Containers: store data (vector, map, set, …).
- Iterators: walk ranges like generalized pointers.
- Algorithms: sort, find, count on [begin, end).
- Adapters: stack, queue, priority_queue.
Why use the STL?
- Saves development time — no hand-rolled dynamic arrays or trees for common cases.
- Highly optimized and well-tested.
- Shorter, more readable code.
- Improves maintainability — teammates know
vector/mapAPIs. - Lets you focus on **problem logic**, not low-level details.
| Benefit | What you gain |
|---|---|
| Speed of coding | Ready containers and algorithms |
| Reliability | Battle-tested implementations |
| Performance | Optimized growth, hashing, sorting |
| Readability | Idiomatic C++ everyone recognizes |
| Safety | RAII ownership, bounds-aware APIs (at) |
Components of the STL
- Think of six cooperating parts — you will use the first three constantly.
| Component | Role | Examples |
|---|---|---|
| Containers | Store and organize data | vector, map, set |
| Algorithms | Operate on data ranges | sort, find, count |
| Iterators | Traverse like generalized pointers | begin(), end() |
| Function objects | Callable objects for algorithms | comparators, lambdas |
| Adapters | Restricted / remapped interfaces | stack, queue |
| Allocators | Memory strategy for containers | default allocator |
Categories of containers
- Pick a category from how you need to store and access data.
| Category | Idea | Examples |
|---|---|---|
| Sequence | Linear order | vector, deque, list, array, forward_list |
| Associative | Sorted unique (or multi) keys | set, multiset, map, multimap |
| Unordered | Hash-based keys | unordered_set, unordered_map |
| Adapters | Restricted interface on top of a container | stack, queue, priority_queue |
Container overview at a glance
- Quick comparison — details live on each container’s lesson page.
| Container | Type | Order | Duplicates | Random access |
|---|---|---|---|---|
vector | Sequence | Insertion order | Yes | Yes O(1) |
deque | Sequence | Insertion order | Yes | Yes O(1) |
list | Sequence | Insertion order | Yes | No |
array | Sequence (fixed) | Fixed | Yes | Yes O(1) |
set / map | Associative | Sorted by key | No (unique keys) | No |
multiset / multimap | Associative | Sorted by key | Yes | No |
unordered_set / map | Unordered | Hash order | No (unique keys) | No |
Common containers — quick demos
- A taste of the containers you will use most often.
- Follow the dedicated pages for full APIs.
#include <iostream>
#include <vector>
#include <list>
#include <set>
#include <map>
#include <string>
#include <unordered_set>
using namespace std;
int main() {
vector<int> v = {10, 20, 30};
v.push_back(40);
for (int x : v) cout << x << " ";
cout << "\n";
list<int> lst;
lst.push_back(2);
lst.push_front(1);
set<int> s = {3, 1, 2, 2}; // {1,2,3}
map<string, int> m{{"A", 10}, {"B", 20}};
unordered_set<int> us = {5, 1, 5};
return 0;
} Common algorithms
- Algorithms live mainly in
and work on **iterator ranges**, not “on the container” directly. - Pattern:
algo(first, last, …)where[first, last)is a half-open range.
| Algorithm | Header | What it does | Example |
|---|---|---|---|
sort | | Sort ascending (default) | sort(v.begin(), v.end()) |
find | | Search for a value | find(v.begin(), v.end(), 3) |
count | | Count matches | count(v.begin(), v.end(), 2) |
reverse | | Reverse range | reverse(v.begin(), v.end()) |
max_element | | Largest element | *max_element(v.begin(), v.end()) |
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> v = {4, 1, 3, 2};
sort(v.begin(), v.end());
reverse(v.begin(), v.end());
cout << count(v.begin(), v.end(), 2) << "\n";
cout << *max_element(v.begin(), v.end()) << "\n";
return 0;
} Iterators
- Iterators act like **generalized pointers** to walk a container.
begin()→ first element;end()→ **one past** the last element.- Also:
rbegin/rend(reverse),cbegin/cend(const). - Algorithms + iterators = same
sort/findworks on many containers.
| Iterator | Meaning |
|---|---|
begin() / end() | Forward range [begin, end) |
cbegin() / cend() | Const forward range |
rbegin() / rend() | Reverse range |
*it / ++it | Dereference / advance |
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> v = {10, 20, 30};
for (auto it = v.begin(); it != v.end(); ++it)
cout << *it << " ";
cout << "\n";
return 0;
} Container adapters
- Adapters provide a **restricted** interface on top of another container.
- **stack** — LIFO (last in, first out).
- **queue** — FIFO (first in, first out).
- **priority_queue** — largest (by default) comes out first (heap).
| Adapter | Access style | Typical ops |
|---|---|---|
stack | LIFO | push, pop, top |
queue | FIFO | push, pop, front |
priority_queue | Priority / heap | push, pop, top |
#include <iostream>
#include <stack>
#include <queue>
using namespace std;
int main() {
stack<int> st;
st.push(1); st.push(2);
cout << st.top() << "\n"; // 2
queue<int> q;
q.push(10); q.push(20);
cout << q.front() << "\n"; // 10
priority_queue<int> pq;
pq.push(3); pq.push(9);
cout << pq.top() << "\n"; // 9
return 0;
} Advantages & use cases
- **Advantages:** less code, optimized, reliable, readable, maintainable.
- **Use cases:** data management, search/sort, graphs (adjacency lists), caches, competitive programming, production apps.
- Next steps in this tutorial: dive into
vector, then sequences, then set/map families.
Key points to remember
- STL = containers + iterators + algorithms (+ adapters/functors).
- Algorithms take **iterator ranges**, not containers by name.
end()is past-the-end — never dereference it.- Prefer
vectoras the default sequence container. - Choose
map/setfor sorted keys;unordered_*for average O(1). - Adapters (
stack/queue) hide full container APIs on purpose.
Advanced — STL Overview
How the pieces connect
- Container holds data → iterators point into it → algorithms consume iterator pairs.
- Same
sortworks onvectorand raw arrays because both expose random-access iterators. - Lambdas/functors customize algorithms (
sortcomparator,find_ifpredicate).
Choosing a container
- Need fast index access and growth at the end → **
vector**. - Need frequent insert/erase in the middle → consider **
list** (benchmark;vectoroften still wins). - Need sorted unique keys → **
set/map**; fast lookup without order → **unordered_***. - Need only push/pop ends with LIFO/FIFO → **adapters**.
| Need | Prefer |
|---|---|
| Dynamic array | vector |
| Front + back ops | deque |
| Dictionary / counter | unordered_map or map |
| Unique sorted IDs | set |
| Undo stack | stack |
| Task queue / BFS | queue |
| Top score / scheduling | priority_queue |
Complexity mindset
- Know big-O for the ops you call:
vectorrandom access O(1), mid insert O(n). - Associative (tree) lookup O(log n); unordered average O(1).
- Interviewers expect you to pick containers with complexity in mind.
Headers cheat sheet
- Include what you use — common headers below.
| Header | Provides |
|---|---|
| vector |
, | deque, list |
, | ordered associative |
, | hash containers |
, | adapters (+ priority_queue in queue) |
| sort, find, count, … |
| iterator utilities |
| accumulate, iota, … |
Functors and lambdas in the STL
- Algorithms accept callables: function pointers, functors, **lambdas**.
- Modern C++ prefers lambdas for one-off predicates and comparators.
- Covered deeper on the Lambdas / Move / RAII page.
Design tips
- Default to
vector+ algorithms + lambdas. - Do not micro-optimize with
listunless profiling says so. - Prefer range-for when you only need elements, iterators when you need positions.
- Use
at()when you want bounds checking;[]when you know indices are valid.
Tricky Interview Points
Q1) What is the STL?
Answer The Standard Template Library: a part of the C++ standard library providing generic containers, iterators, algorithms, and related utilities.
Q2) What are the main components of the STL?
Answer Containers, algorithms, and iterators are primary; also function objects, adapters, and allocators.
Q3) What are sequence containers?
Answer Containers that store elements in linear order, e.g. vector, deque, list, array, forward_list.
Q4) map vs unordered_map?
Answer map keeps keys sorted (tree, O(log n)); unordered_map uses hashing (average O(1)) with no sorted order.
Q5) Why do algorithms use iterators?
Answer So one algorithm can work on many containers (and arrays) through a common range interface [first, last).
Q6) What does end() point to?
Answer One past the last element — it must not be dereferenced.
Q7) What is a container adapter?
Answer A restricted interface on top of another container — stack (LIFO), queue (FIFO), priority_queue (heap).
Q8) Which container is the default choice for a dynamic array?
Answer std::vector.
Q9) Name five common algorithms.
Answer sort, find, count, reverse, max_element (among many others).
Q10) set vs multiset?
Answer set stores unique sorted keys; multiset allows duplicate keys, still sorted.
Q11) Advantages of using the STL?
Answer Faster development, optimized and tested code, better readability and maintainability.
Q12) Do algorithms take containers as arguments?
Answer They take iterator ranges (and sometimes output iterators), not the container object itself.
Simple Programs
vector + sort + range-for
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> v = {5, 2, 8, 1};
sort(v.begin(), v.end());
for (int x : v) cout << x << " ";
cout << "\n";
return 0;
} find and count
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> v = {1, 2, 2, 3};
auto it = find(v.begin(), v.end(), 2);
if (it != v.end()) cout << "found\n";
cout << count(v.begin(), v.end(), 2) << "\n";
return 0;
} map iteration
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
map<string, int> ages{{"Ann", 20}, {"Bob", 22}};
for (auto& [k, v] : ages)
cout << k << " " << v << "\n";
return 0;
} set uniqueness
#include <iostream>
#include <set>
using namespace std;
int main() {
set<int> s = {3, 1, 2, 2, 1};
for (int x : s) cout << x << " ";
cout << "\n";
return 0;
} stack and queue
#include <iostream>
#include <stack>
#include <queue>
using namespace std;
int main() {
stack<char> st;
st.push('A'); st.push('B');
cout << st.top() << "\n";
queue<char> q;
q.push('A'); q.push('B');
cout << q.front() << "\n";
return 0;
} Iterator walk
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
vector<string> w = {"STL", "rocks"};
for (auto it = w.begin(); it != w.end(); ++it)
cout << *it << "\n";
return 0;
} Problem Solving Tricks
- STL = containers + iterators + algorithms.
- Algorithms use [begin, end) ranges — never dereference end().
- Default sequence container: vector.
- map/set sorted; unordered_* hashed.
- Adapters: stack LIFO, queue FIFO, priority_queue heap.
- Prefer range-for for simple traversal.
- Lambdas customize sort/find_if cleanly.
- Include the right header for each container/algorithm.
- Know complexity before picking a container.
- STL is template-based — types must support needed ops.
- Focus on logic; let STL handle data structure details.
- Next: deep-dive vector, then set/map pages in this course.
Practice Programs List
- Create a vector, sort it, and print with range-for.
- Use find and count on a vector of ints.
- Build a map of names to ages; print key/value pairs.
- Fill a set from an array with duplicates; show unique sorted output.
- Push/pop a stack and print top after each change.
- Simulate a queue of tasks with push/front/pop.
- Walk a vector with iterators (not range-for) and print indices mentally.
- Write a choose-table: vector vs list vs deque for three scenarios.
- Sort a vector descending with a lambda comparator.
- List the header needed for vector, map, algorithm, stack.
- Explain in comments what end() means on a diagram of 4 elements.
- Name one real app feature you would build with unordered_map.