pop_heap() in C++

This C++ program pops element from heap using pop_heap algorithm. The pop_heap operation swaps the element at first position and the last position and makes the subrange [first, last – 1) into a max-heap. The element at the last position is actually popped from the container.

Here is the source code of the C++ program which pops element from heap using pop_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 pop largest element from heap using pop_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, 4, 1, 6};
  22.     std::vector<int> v(arr, arr + sizeof(arr)/sizeof(int));
  23.     int largest;
  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 << "Heap : ";
  30.     print(v);
  31.     // moves the largest element to the end of heap
  32.     pop_heap(v.begin(), v.end());
  33.     largest = v.back();
  34.     std::cout << "Largest Element : " << largest << std::endl;
  35.     v.pop_back(); // removes the largest element
  36.     std::cout << "Heap : ";
  37.     print(v);
  38. }

$ a.out
vector v : 1 5 3 4 1 6 
Heap : 6 5 3 4 1 1 
Largest Element : 6
Heap : 5 4 3 1 1

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.