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.
/*
* C++ Program to pop largest element from heap using pop_heap() operation
*/
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
void print(const std::vector <int>& v)
{
std::vector <int>::const_iterator i;
for(i = v.begin(); i != v.end(); i++)
{
std::cout << *i << " ";
}
std::cout << std::endl;
}
int main()
{
int arr[] = {1, 5, 3, 4, 1, 6};
std::vector<int> v(arr, arr + sizeof(arr)/sizeof(int));
int largest;
std::cout << "vector v : ";
print(v);
// default make_heap creates max-heap
std::make_heap(v.begin(), v.end());
std::cout << "Heap : ";
print(v);
// moves the largest element to the end of heap
pop_heap(v.begin(), v.end());
largest = v.back();
std::cout << "Largest Element : " << largest << std::endl;
v.pop_back(); // removes the largest element
std::cout << "Heap : ";
print(v);
}
$ 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.
Related Posts:
- Apply for Computer Science Internship
- Check Programming Books
- Practice Programming MCQs
- Check C++ Books
- Check Computer Science Books