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.
/*
* C++ Program to push elements to heap using push_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, 2, 4, 6};
std::vector <int> v(arr, arr + sizeof(arr) / sizeof(int));
std::cout << "vector v : ";
print(v);
// default make_heap creates max-heap
std::make_heap(v.begin(), v.end());
std::cout << "Heap : ";
print(v);
v.push_back(7);
push_heap(v.begin(), v.end());
std::cout << "Heap after push : ";
print(v);
}
$ 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.
Related Posts:
- Apply for Computer Science Internship
- Check Programming Books
- Practice Programming MCQs
- Check C++ Books
- Practice Computer Science MCQs