CodeNebula
C++20stladvanced

std::ranges::push_heap / pop_heap / make_heap / sort_heap (C++20 Addition)

C++20 · The Big Four · Compiler flag: -std=c++20

Explanation

Heap operations on ranges. `make_heap` arranges elements into a max-heap. `push_heap`/`pop_heap` maintain the heap property after insertion/removal. `sort_heap` sorts a heap into ascending order.

Real-World Scenario

Implement a priority queue for a task scheduler using heap operations on a flat vector.

Quick Snippet

snippet.cpp
#include <ranges>
#include <algorithm>
#include <vector>

std::vector<int> tasks = {3, 1, 4, 1, 5};
std::ranges::make_heap(tasks);

tasks.push_back(9);
std::ranges::push_heap(tasks);

std::ranges::pop_heap(tasks);
int highest = tasks.back();  // 9
tasks.pop_back();

Full Example

ranges_heap.cpp
// CodeNebula - C++20 Example: Ranges Heap Operations
// Compile: g++ -std=c++20 -Wall -Wextra -o example ranges_heap.cpp

#include <algorithm>
#include <iostream>
#include <vector>

void print(const char* label, const std::vector<int>& v) {
    std::cout << label;
    for (int x : v) std::cout << x << ' ';
    std::cout << '\n';
}

int main() {
    // ranges::make_heap - build a max-heap from unsorted data
    std::vector<int> heap = {3, 1, 4, 1, 5, 9, 2, 6};
    print("Original:   ", heap);

    std::ranges::make_heap(heap);
    print("Make heap:  ", heap);

    // ranges::push_heap - add an element to the heap
    heap.push_back(8);
    std::ranges::push_heap(heap);
    print("Push 8:     ", heap);

    heap.push_back(7);
    std::ranges::push_heap(heap);
    print("Push 7:     ", heap);

    // ranges::pop_heap - move the largest element to the end
    std::ranges::pop_heap(heap);
    std::cout << "Popped max: " << heap.back() << '\n';
    heap.pop_back();
    print("After pop:  ", heap);

    // Pop another
    std::ranges::pop_heap(heap);
    std::cout << "Popped max: " << heap.back() << '\n';
    heap.pop_back();
    print("After pop:  ", heap);

    // ranges::sort_heap - sort a heap into ascending order
    std::vector<int> to_sort = {5, 3, 8, 1, 7, 2, 9, 4};
    std::ranges::make_heap(to_sort);
    print("\nHeap:       ", to_sort);

    std::ranges::sort_heap(to_sort);
    print("Sort heap:  ", to_sort);

    // Min-heap using greater comparator
    std::vector<int> min_heap = {6, 2, 8, 1, 4};
    std::ranges::make_heap(min_heap, std::ranges::greater{});
    print("\nMin heap:   ", min_heap);
    std::cout << "Min element at front: " << min_heap.front() << '\n';

    std::ranges::pop_heap(min_heap, std::ranges::greater{});
    std::cout << "Popped min: " << min_heap.back() << '\n';
    min_heap.pop_back();

    return 0;
}
Run command
g++ -std=c++20 -Wall -Wextra -o example ranges_heap.cpp