sort_heap() in C++ STL

The C++ Standard Library consists of the header, <algorithm> which defines a collection of functions (principally designed to deal with a range of elements). sort_heap() is a method in the STL that sorts a certain range of a heap in ascending order.

The range loses its properties as a heap.


sort_heap( iterator_begin, iterator_end, comparator ); //comparator is optional

Parameters: The sort_heap() method accepts 3 parameters

  • iterator_begin: Iterator to the initial position of heap
  • iterator_end: Iterator to the final position of heap ( Note: the range is [iterator_begin,iterator_end) )
  • comparator: Binary function that accepts two elements in the range as arguments, and returns a value convertible to bool.

Return value: none

Example of sort_heap() method


using namespace std;

int main()
    vector<int> v;

    cout<<"Before heap: "<<v.front()<<endl; //first value

    make_heap(v.begin(), v.end());
    cout<<"After heap: "<<v.front()<<endl;

    cout<<"Sorted heap (ascending): \n";
    for( int i = 0; i < v.size() ; i++)
        cout<<v[i]<<"  ";

    cout<<"Sorted heap (descending): \n";
    sort_heap(v.begin(),v.end(), greater<int> ());
    for( int i = 0; i < v.size() ; i++)
        cout<<v[i]<<"  ";


Before heap: 4
After heap: 8
Sorted heap (ascending):
-5  3  4  7  8
Sorted heap (descending):
8  7  4  3  -5

This article is written by

Please comment below, if you have any doubts or find any error in the above article.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top

Full Stack Integrated Bootcamp Free Trial

  • Please enter a number from 7000000000 to 9999999999.