Learn C++
#include "stlalgorithms/alg_heaps.hpp"

Heap & Set Operations in C++

//concept

Beyond sorting, <algorithm> offers heap primitives (make_heap, push_heap, pop_heap) that turn any random-access range into a max-heap in place — the DIY behind priority_queue — plus sorted-range set operations (set_union, set_intersection, set_difference) and merging. min/max/clamp and minmax_element cover extrema, while lexicographical_compare orders ranges like words.

Heaps suit repeated max-extraction from plain vectors without the priority_queue wrapper; set operations answer union/intersection questions on sorted data in linear time. All demand sorted input where documented — feed unsorted ranges and the answers are silently wrong.

//how it works
1

Heapify any range

make_heap(v.begin(), v.end()) arranges a max-heap in O(n); push_heap/pop_heap maintain it per insertion/removal in O(log n).

2

Set ops need sorted input

set_union/intersection/difference merge two sorted ranges in O(n) — sort both sides first, or the output is garbage.

3

Extrema in one pass

min/max/clamp bound single values; minmax_element finds both ends of a range together, cheaper than two passes.

4

Compare ranges like words

lexicographical_compare orders sequences element by element — dictionary order for vectors and strings alike.

//example
#include <iostream>
#include <vector>
#include <algorithm>
 
int main() {
std::vector<int> v{3, 1, 2};
std::make_heap(v.begin(), v.end());
std::cout << v.front() << std::endl;
std::pop_heap(v.begin(), v.end());
v.pop_back();
std::cout << v.front() << std::endl;
return 0;
}
Output
3
2
1make_heap rearranges into a valid max-heap in O(n) — the largest element (3) sits at front.
2pop_heap moves the max to the back (still inside the range); pop_back then removes it for real.
3The remaining heap's front is now 2 — repeated max extraction without any wrapper class.
//use cases
Priority handling on plain vectors without committing to priority_queue
Union/intersection/difference of sorted ID lists in linear time
Clamping sensor and UI values with std::clamp
Dictionary-order comparisons of version vectors and words

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.