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.
/*
* C++ Program to create heap using make_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[] = {10, 20, 30, 40, 50, 60};
std::vector <int> v(arr, arr + sizeof(arr)/sizeof(int));
std::vector <int>::iterator i;
std::cout << "vector v : ";
print(v);
// default make_heap creates max-heap
std::make_heap(v.begin(), v.end());
std::cout << "Front Element of max-heap = "
<< v.front() << std::endl;
std::cout << "max-heap : ";
print(v);
// make_heap with greater predicate creates min-heap
std::make_heap(v.begin(), v.end(), std::greater <int>());
std::cout << "Front Element of min-heap = "
<< v.front() << std::endl;
std::cout << "min-heap : ";
print(v);
}
$ 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.
Related Posts:
- Check C++ Books
- Practice Computer Science MCQs
- Check Computer Science Books
- Apply for C++ Internship
- Practice Programming MCQs