Sunday, November 17, 2024
Google search engine

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 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_head(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. 

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments