Heap & Set Operations in C++
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.
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).
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.
Extrema in one pass
min/max/clamp bound single values; minmax_element finds both ends of a range together, cheaper than two passes.
Compare ranges like words
lexicographical_compare orders sequences element by element — dictionary order for vectors and strings alike.
#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;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself — building beats watching.