push_heap() in C++

This C++ program pushes elements to heap using push_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 push_heap inserts the elements into the heap at last – 1 position where the heap is defined in [first, last – 1). The push_heap assumes the range [first, last – 1) is a valid heap.

Here is the source code of the C++ program which pushes elements to heap using push_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 push elements to heap using push_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[] = {1, 5, 3, 2, 4, 6};
  22.     std::vector <int> v(arr, arr + sizeof(arr) / sizeof(int));
  23.  
  24.     std::cout << "vector v : ";
  25.     print(v);
  26.     // default make_heap creates max-heap
  27.     std::make_heap(v.begin(), v.end());
  28.     std::cout << "Heap : ";
  29.     print(v);
  30.     v.push_back(7);
  31.     push_heap(v.begin(), v.end());
  32.     std::cout << "Heap after push : ";
  33.     print(v);
  34. }

$ a.out
vector v : 1 5 3 2 4 6 
Heap : 6 5 3 2 4 1
Heap after push : 7 5 6 2 4 1 3

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

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

If you find any mistake above, kindly email to [email protected]

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.