Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::sort_heap — sorting an existing heap

std::sort_heap turns a heap into a sorted range. It requires random-access iterators and a range that is a valid heap under the comparison the function uses; it does not sort arbitrary input directly.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <algorithm>

 template<class RandomAccessIterator>
constexpr void sort_heap(RandomAccessIterator first, RandomAccessIterator last);

template<class RandomAccessIterator, class Compare>
constexpr void sort_heap(RandomAccessIterator first, RandomAccessIterator last, Compare comp);

std::sort_heap, declared in <algorithm>, sorts the elements of [first, last) in place and returns void. The range must already be a valid heap under the comparison used by std::sort_heap. For arbitrary input, first call std::make_heap, or use std::sort directly.

The overload without comp produces nondecreasing order for numbers. A custom comp must define a strict weak ordering. That ordering need not match the one used to build the heap, as long as the range is a valid heap under comp. For example, using std::greater<int>{} in both std::make_heap and std::sort_heap produces nonincreasing output. Passing a range that is not an appropriate heap violates a precondition.

Random-access iterators are required, and elements must satisfy the swappability, move-construction, and move-assignment requirements. For N = last - first, the algorithm performs at most 2 N log N comparisons. Stability—preserving the order of elements equivalent under the comparison—is not guaranteed. The result is sorted; do not assume it remains a heap under the same ordering.

The example first builds a heap from five numbers, then sorts it into 1 2 3 4 5. This entry describes the classic std::sort_heap overloads, not the separate std::ranges::sort_heap interface. The source is the current standard draft; the example is intended for local verification with -std=c++23.

Examples

#include <algorithm>
#include <array>
#include <cstddef>
#include <iostream>

int main() {
    std::array<int, 5> values{4, 1, 5, 2, 3};
    std::make_heap(values.begin(), values.end());
    std::sort_heap(values.begin(), values.end());

    for (std::size_t i = 0; i < values.size(); ++i) {
        if (i != 0) std::cout << ' ';
        std::cout << values[i];
    }
    std::cout << '\n';
}

Result

1 2 3 4 5

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources