×

C++ STL Tutorial

C++ STL Algorithm

C++ STL Arrays

C++ STL String

C++ STL List

C++ STL Stack

C++ STL Set

C++ STL Queue

C++ STL Vector

C++ STL Map

C++ STL Multimap

C++ STL MISC.

Create Heap by using make_heap() | C++ STL

C++ STL make_heap() function: Here, we are going to learn, what is heap data structure? How to create heap using make_heap() in C++ STL (Standard Template Library)?
Submitted by Himanshu Singh Bisht, on November 14, 2018

What is Heap Data structure?

Heap is a tree-based which is used for fast retrieval of largest (max heap) or smallest (min heap) element. This DS is used in the priority queue, prims algo, heap sort and many more.

make_heap() function

Syntax:

    make_heap( arg1, agr2 ,[arg3]) 

Here,

  • arg1 = pointer or iterator to starting of the number list
  • arg2 = pointer or iterator to ending of the number list
  • arg3 = optional, use to change default nature of the heap i.e is max heap to min heap

Code to demonstrate use of make_heap()[max heap]

#include <bits/stdc++.h>
using namespace std;

#define MAX 5

int main() {
  int array[MAX] = {6, 3, 6, 17, 8};
  // Max Heap created
  
  make_heap(array, array + MAX);
  
  cout << array[0] << endl;
  
  return 0;
}

Output

17

Code to demonstrate use of make_heap()[min heap]

#include <bits/stdc++.h>
using namespace std;
#define MAX 5

bool compare(int a, int b) {
  if (a < b)
    return 0;  // change to 1 if max heap required
  else
    return 1;  // change to 0 if max heap required
}

int main() {
  int array[MAX] = {6, 3, 6, 17, 8};

  make_heap(array, array + MAX, compare);

  cout << array[0] << endl;

  return 0;
}

Output

3

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.