Skip to main content

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.

L1

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.
IdeaMeaning
STLPart of the C++ standard library
TemplatesGeneric code for many types
ContainersStore and organize data
AlgorithmsOperate on ranges via iterators
GoalLess 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.

C++ STL overview infographic: what is STL, components, container categories, container comparison table, vector list set map unordered_set examples, common algorithms, iterators, adapters stack queue priority_queue, advantages and use cases.
C++ STL — focus on logic, not low-level data structure details
  • 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/map APIs.
  • Lets you focus on **problem logic**, not low-level details.
BenefitWhat you gain
Speed of codingReady containers and algorithms
ReliabilityBattle-tested implementations
PerformanceOptimized growth, hashing, sorting
ReadabilityIdiomatic C++ everyone recognizes
SafetyRAII ownership, bounds-aware APIs (at)

Components of the STL

  • Think of six cooperating parts — you will use the first three constantly.
ComponentRoleExamples
ContainersStore and organize datavector, map, set
AlgorithmsOperate on data rangessort, find, count
IteratorsTraverse like generalized pointersbegin(), end()
Function objectsCallable objects for algorithmscomparators, lambdas
AdaptersRestricted / remapped interfacesstack, queue
AllocatorsMemory strategy for containersdefault allocator

Categories of containers

  • Pick a category from how you need to store and access data.
CategoryIdeaExamples
SequenceLinear ordervector, deque, list, array, forward_list
AssociativeSorted unique (or multi) keysset, multiset, map, multimap
UnorderedHash-based keysunordered_set, unordered_map
AdaptersRestricted interface on top of a containerstack, queue, priority_queue

Container overview at a glance

  • Quick comparison — details live on each container’s lesson page.
ContainerTypeOrderDuplicatesRandom access
vectorSequenceInsertion orderYesYes O(1)
dequeSequenceInsertion orderYesYes O(1)
listSequenceInsertion orderYesNo
arraySequence (fixed)FixedYesYes O(1)
set / mapAssociativeSorted by keyNo (unique keys)No
multiset / multimapAssociativeSorted by keyYesNo
unordered_set / mapUnorderedHash orderNo (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.
AlgorithmHeaderWhat it doesExample
sortSort ascending (default)sort(v.begin(), v.end())
findSearch for a valuefind(v.begin(), v.end(), 3)
countCount matchescount(v.begin(), v.end(), 2)
reverseReverse rangereverse(v.begin(), v.end())
max_elementLargest 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/find works on many containers.
IteratorMeaning
begin() / end()Forward range [begin, end)
cbegin() / cend()Const forward range
rbegin() / rend()Reverse range
*it / ++itDereference / 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).
AdapterAccess styleTypical ops
stackLIFOpush, pop, top
queueFIFOpush, pop, front
priority_queuePriority / heappush, 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 vector as the default sequence container.
  • Choose map/set for sorted keys; unordered_* for average O(1).
  • Adapters (stack/queue) hide full container APIs on purpose.
L2

Advanced — STL Overview

How the pieces connect

  • Container holds data → iterators point into it → algorithms consume iterator pairs.
  • Same sort works on vector and raw arrays because both expose random-access iterators.
  • Lambdas/functors customize algorithms (sort comparator, find_if predicate).

Choosing a container

  • Need fast index access and growth at the end → **vector**.
  • Need frequent insert/erase in the middle → consider **list** (benchmark; vector often still wins).
  • Need sorted unique keys → **set/map**; fast lookup without order → **unordered_***.
  • Need only push/pop ends with LIFO/FIFO → **adapters**.
NeedPrefer
Dynamic arrayvector
Front + back opsdeque
Dictionary / counterunordered_map or map
Unique sorted IDsset
Undo stackstack
Task queue / BFSqueue
Top score / schedulingpriority_queue

Complexity mindset

  • Know big-O for the ops you call: vector random 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.
HeaderProvides
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 list unless 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.
L3

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.

L4

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;
}
L5

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.
L6

Practice Programs List

  1. Create a vector, sort it, and print with range-for.
  2. Use find and count on a vector of ints.
  3. Build a map of names to ages; print key/value pairs.
  4. Fill a set from an array with duplicates; show unique sorted output.
  5. Push/pop a stack and print top after each change.
  6. Simulate a queue of tasks with push/front/pop.
  7. Walk a vector with iterators (not range-for) and print indices mentally.
  8. Write a choose-table: vector vs list vs deque for three scenarios.
  9. Sort a vector descending with a lambda comparator.
  10. List the header needed for vector, map, algorithm, stack.
  11. Explain in comments what end() means on a diagram of 4 elements.
  12. Name one real app feature you would build with unordered_map.