make_heap() in C++ STL

Last Updated : 20 Jan, 2026

make_heap() transforms a sequence into a heap, allowing O(1) access to the largest (or smallest) element, while the order of other elements is implementation-dependent. It is defined in the <algorithm> header.

Syntax 1 : make_heap(iter_first, iter_last)

void make_heap(RandomAccessIterator first, RandomAccessIterator last);

Parameters:

  • first : Iterator pointing to the first element of the sequence to be transformed into a heap.
  • last : Iterator pointing to one past the last element of the sequence to be transformed into a heap.

Code:

C++
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;

int main() {
    vector<int> v = { 4, 6, 7, 9, 11, 4 };
    
    // Using make_heap() to transform vector into a max heap
    make_heap(v.begin(),v.end());
    // Checking if heap using front() function
    cout << "The maximum element of heap is : ";
    cout << v.front();
}

Output
The maximum element of heap is : 11

Syntax 2 : make_heap(iter_first, iter_last, comp)

void make_heap(RandomAccessIterator first, RandomAccessIterator last, Compare comp);

Parameters:

  • first : Iterator pointing to the first element of the sequence to be transformed into a heap.
  • last : Iterator pointing to one past the last element of the sequence.
  • comp : Comparator function or function object that takes two elements and returns true or false to determine the heap order. It cannot modify the elements.

Code:

C++
#include<iostream>
#include<algorithm> 
#include<vector>
using namespace std;

struct greaters{
    bool operator()(const long& a,const long& b) const{
        return a>b;
    }
};

int main() {
    vector<int> v = { 15, 6, 7, 9, 11, 45 };
  
    make_heap(v.begin(),v.end(), greaters());
    cout << "The minimum element of heap is : ";
    cout << v.front();
}

Output
The minimum element of heap is : 6

Possible application : This function can be used in scheduling problems, where new elements are inserted dynamically in iterations. Sorting the entire sequence repeatedly to get the maximum is costly with O(n log n) complexity. Instead, we can use push_heap() to re-heapify the existing heap in O(log n) time. The code below demonstrates its implementation.

Implementation:

C++
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;

int main() {
  
    vector<int> vi = { 15, 6, 7, 9, 11, 19};

    int k = 3;
    make_heap(vi.begin(),vi.end());
    int a = 10;
    
    for ( int i=0; i<k; i++){
    vi.push_back(a);
    push_heap(vi.begin(), vi.end());
    cout << "Job with maximum priority is : ";
    cout << vi.front() << endl;

    a = a + 10;
    
    }
  	return 0;
}

Output
Job with maximum priority is : 19
Job with maximum priority is : 20
Job with maximum priority is : 30
Comment