make_heap() in C++

This C++ program creates a heap using make_heap algorithm. A heap is a way to organize the elements of a range that allows for fast retrieval of the element with the highest value at any moment. The make_heap rearranges the elements in the container in such a way that they form a heap.

Here is the source code of the C++ program which creates a heap using make_heap algorithm. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to create heap using make_heap() operation
  3.  */
  4. #include <iostream>
  5. #include <vector>
  6. #include <algorithm>
  7. #include <functional>
  8.  
  9. void print(const std::vector <int>& v)
  10. {
  11.     std::vector <int>::const_iterator i;
  12.     for(i = v.begin(); i != v.end(); i++)
  13.     {
  14.         std::cout << *i << " ";
  15.     }
  16.     std::cout << std::endl;
  17. }
  18.  
  19. int main()
  20. {
  21.     int arr[] = {10, 20, 30, 40, 50, 60};
  22.     std::vector <int> v(arr, arr + sizeof(arr)/sizeof(int));
  23.     std::vector <int>::iterator i;
  24.  
  25.     std::cout << "vector v : ";
  26.     print(v);
  27.     // default make_heap creates max-heap
  28.     std::make_heap(v.begin(), v.end());
  29.     std::cout << "Front Element of max-heap = "
  30.               << v.front() << std::endl;
  31.     std::cout << "max-heap : ";
  32.     print(v);
  33.     // make_heap with greater predicate creates min-heap
  34.     std::make_heap(v.begin(), v.end(), std::greater <int>());
  35.     std::cout << "Front Element of min-heap = "
  36.               << v.front() << std::endl;
  37.     std::cout << "min-heap : ";
  38.     print(v);
  39. }

$ a.out
vector v : 10 20 30 40 50 60 
Front Element of max-heap = 60
max-heap : 60 50 30 40 20 10 
Front Element of min-heap = 10
min-heap : 10 20 30 40 50 60

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.