Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • C++
  • Standard Template Library
  • STL Vector
  • STL List
  • STL Set
  • STL Map
  • STL Stack
  • STL Queue
  • STL Priority Queue
  • STL Interview Questions
  • STL Cheatsheet
  • C++ Templates
  • C++ Functors
  • C++ Iterators
Open In App
Next Article:
make_heap() in C++ STL
Next article icon

Heap in C++ STL

Last Updated : 20 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The heap data structure can be implemented in a range using STL which provides faster max or min item retrieval, and faster insertion and deletion on sorted data and also works as a sub-routine for heapsort.

STL Functions for Heap Operations

  1. make_heap(): Converts given range to a heap.
  2. push_heap(): Arrange the heap after insertion at the end.
  3. pop_heap(): Moves the max element at the end for deletion.
  4. sort_heap(): Sort the elements of the max_heap to ascending order.
  5. is_heap(): Checks if the given range is max_heap.
  6. is_heap_until(): Returns the largest sub-range that is max_heap.

All of the above functions are defined inside the <algorithm> header file.

1. make_heap() Function

The std::make_heap() function is used to convert the given range in a container to a heap. By default, it generates the max heap but we can use a custom comparator to change it to the min heap.

Syntax:

std::make_heap(begin_iterator, end_iterator);

The iterators provided must be of randomAccessIterator type.

In the below examples, we will be using vector containers to make a heap.

Example:

C++
// C++ code to demonstrate the working of // make_heap(), front() #include <bits/stdc++.h> using namespace std; int main() {     // Initializing a vector     vector<int> v1 = { 20, 30, 40, 25, 15 };      // Converting vector into a heap     // using make_heap()     make_heap(v1.begin(), v1.end());      // Displaying the maximum element of heap     // using front()     cout << "The maximum element of heap is : ";     cout << v1.front() << endl;      return 0; } 

Output
The maximum element of heap is : 40 

Complexity of the above method:

Time Complexity: O(N), where N is the number of elements.
Auxiliary Space: O(1),since no extra space is used.

We have used the front() function in the above example to show the element at the front of the heap. It is a member function of std::vector class that displays the first element of the vector container which in the case of a heap provides the most prioritized element.

To know more about make_heap() function, refer to this article - make_heap() in C++ STL

2. push_heap() Function

The std::push_heap() function is used to sort the heap after the insertion of an element at the end of the heap. We use the push_back() function of std::vector class to insert a new element at the end of the vector then use the push_heap() function to place that element at its appropriate position.

Syntax:

std::push_heap(begin_interator, end_iterator);

Example:

C++
// C++ program to demonstrate the use of push_heap() // function #include <algorithm> #include <iostream> #include <vector> using namespace std;  void print(vector<int>& vc) {     for (auto i : vc) {         cout << i << " ";     }     cout << endl; }  int main() {     vector<int> vc{ 20, 30, 40, 10 };      make_heap(vc.begin(), vc.end());     cout << "Initial Heap: ";     print(vc);      vc.push_back(50);     cout << "Heap just after push_back(): ";     print(vc);     push_heap(vc.begin(), vc.end());     cout << "Heap after push_heap(): ";     print(vc);      return 0; } 

Output
Initial Heap: 40 30 20 10  Heap just after push_back(): 40 30 20 10 50  Heap after push_heap(): 50 40 20 10 30  

Time Complexity: O(logN), where N is the number of elements.

Note: The push_heap() function should only be used after the insertion of a single element at the back. This function behavior is undefined if used for random insertion or to build a heap. For these cases, make_heap() function should be used.

3. pop_heap() Function

The std::pop_heap() function is used to move the largest element at the end of the heap so that we can safely remove the element without destroying the heap. Then we use the pop_back() function of std::vector class to actually remove that element.

Syntax:

std::pop_heap(begin_iterator, end_iterator);

Example:

C++
#include <bits/stdc++.h> using namespace std;  void print(vector<int>& vc) {     for (auto i : vc) {         cout << i << " ";     }     cout << endl; }  int main() {     // initial vector     vector<int> vc{ 40, 10, 20, 50, 30 };      // making heap     make_heap(vc.begin(), vc.end());     cout << "Initial Heap: ";     print(vc);        // using pop_heap() function to move the largest element     // to the end     pop_heap(vc.begin(), vc.end());     cout << "Heap after pop_heap(): ";     print(vc);      // actually removing the element from the heap using     // pop_back()     vc.pop_back();     cout << "Heap after pop_back(): ";     print(vc);      return 0; } 

Output
Initial Heap: 50 40 20 10 30  Heap after pop_heap(): 40 30 20 10 50  Heap after pop_back(): 40 30 20 10  

Complexity of the above method:

Time Complexity: O(logN), where N is the number of elements.

4. sort_heap()

The std::sort_heap() function is used to sort the heap in ascending order. It uses the heapsort algorithm and only works on the heap.

Below is the implementation of the above method:

C++
// C++ code to demonstrate the working of // sort_heap() #include <bits/stdc++.h> using namespace std; int main() {      // Initializing a vector     vector<int> v1 = { 20, 30, 40, 25, 15 };      // Converting vector into a heap     // using make_heap()     make_heap(v1.begin(), v1.end());      // Displaying heap elements     cout << "The heap elements are: ";     for (int& x : v1)         cout << x << " ";     cout << endl;      // sorting heap using sort_heap()     sort_heap(v1.begin(), v1.end());      // Displaying heap elements     cout << "The heap elements after sorting are: ";     for (int& x : v1)         cout << x << " ";      return 0; } 

Output
The heap elements are: 40 30 20 25 15  The heap elements after sorting are: 15 20 25 30 40 

Complexity of the above method:

Time Complexity: O(NlogN), where N is the number of elements.

5. is_heap() Function

The std::is_heap() function is used to check whether the given range of the container is a heap or not. By default, it checks for max heap but we can also use a comparator to make it work for min heap.

Syntax:

std::is_heap(begin_iterator, end_iterator);

Return Value:

  • true if the given range is max_heap.
  • false if the given range is not a max_heap.

6. is_heap_until() Function

The std::is_heap_until() function returns the iterator to the position till the container is the heap.

Syntax:

std::is_heap_until(begin_iterator, end_iterator);

Return Value: Iterator till which the container is a heap.

Example:

C++
// C++ code to demonstrate the working of // is_heap() and is_heap_until() #include <bits/stdc++.h> using namespace std; int main() {      // Initializing a vector     vector<int> v1 = { 40, 30, 25, 35, 15 };      // Declaring heap iterator     vector<int>::iterator it1;      // Checking if container is heap     // using is_heap()     is_heap(v1.begin(), v1.end())         ? cout << "The container is heap "           : cout << "The container is not heap"; // ternary operator     cout << endl;      // using is_heap_until() to check position     // till which container is heap     auto it = is_heap_until(v1.begin(), v1.end());      // Displaying heap range elements     cout << "The heap elements in container are : ";     for (it1 = v1.begin(); it1 != it; it1++)         cout << *it1 << " ";      return 0; } 

Output
The container is not heap The heap elements in container are : 40 30 25 

Complexity of the above method:

Time Complexity: O(N), where N is the number of elements. 



Next Article
make_heap() in C++ STL

K

kartik
Improve
Article Tags :
  • Heap
  • C++
  • DSA
  • STL
  • CPP-Library
Practice Tags :
  • CPP
  • Heap
  • STL

Similar Reads

    Heap in C++ STL
    The heap data structure can be implemented in a range using STL which provides faster max or min item retrieval, and faster insertion and deletion on sorted data and also works as a sub-routine for heapsort.STL Functions for Heap Operationsmake_heap(): Converts given range to a heap.push_heap(): Arr
    6 min read
    make_heap() in C++ STL
    make_heap() is used to transform a sequence into a heap. A heap is a data structure which points to highest( or lowest) element and making its access in O(1) time. Order of all the other elements depends upon particular implementation, but remains consistent throughout. This function is defined in t
    3 min read
    sort_heap function in C++
    The sort_heap( ) is an STL algorithm which sorts a heap within the range specified by start and end. Sorts the elements in the heap range [start, end) into ascending order. The second form allows you to specify a comparison function that determines when one element is less than another. Defined in h
    3 min read
    std::is_heap( ) in C++ with Examples
    The std::is_heap() function in C++ Standard Template Library is used to check whether a given range of elements forms Max Heap or not. It returns True when given ranges of elements forms Max Heap, else it returns False. Header File: #include <algorithm> Syntax: is_heap(first, last) Parameter:
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences