C++ STL algorithm, make_heap() and push_back() code example
Compiler: Visual C++ Express Edition 2005
Compiled on Platform: Windows XP Pro SP2
Header file: Standard
Additional project setting: Set project to be compiled as C++
Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)
Other info: none
To do: Using the C++ push_heap() to add an element that is at the end of a range to an existing heap consisting of the prior elements in the range and make_heap() to convert elements from a specified range into a heap in which the first element is the largest and for which a sorting criterion may be specified with a binary predicate
To show: How to use the C++ algorithm, push_heap() to add an element that is at the end of a range to an existing heap consisting of the prior elements in the range and make_heap() to convert elements from a specified range into a heap in which the first element is the largest and for which a sorting criterion may be specified with a binary predicate in C++ programming
// C++ STL algorithm, make_heap() example
#include <vector>
#include <algorithm>
#include <functional>
#include <iostream>
using namespace std;
int main(void)
{
int i;
// vector container
vector <int> v1;
// iterator
vector <int>::iterator Iter1;
for (i = 11; i <= 20; i++)
v1.push_back(i);
random_shuffle(v1.begin(), v1.end());
cout<<"Randomly shuffle v1 vector is: ";
for (Iter1 = v1.begin(); Iter1 != v1.end(); Iter1++)
cout<<*Iter1<<" ";
cout<<endl<<endl;
// make v1 a heap with default less-than ordering
make_heap(v1.begin(), v1.end());
cout<<"The heaped version of v1 vector is: ";
for (Iter1 = v1.begin(); Iter1 != v1.end(); Iter1++)
cout<<*Iter1<<" ";
cout<<endl;
// make v1 a heap with greater than ordering
make_heap(v1.begin(), v1.end(), greater<int>());
cout<<"The greater-than heaped version of v1 vector is: ";
for (Iter1 = v1.begin(); Iter1 != v1.end(); Iter1++)
cout<<*Iter1<<" ";
cout<<endl;
return 0;
}
Output examples:
Randomly shuffle v1 vector is: 19 12 20 13 11 16 18 14 15 17
The heaped version of v1 vector is: 20 17 19 15 12 16 18 14 13 11
The greater-than heaped version of v1 vector is: 11 12 16 13 17 19 18 14 15 20
Press any key to continue . . .