C++ STL algorithm, make_heap() program example

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

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++ 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

To show: How to use the C++ algorithm, 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()

#include <vector>

#include <algorithm>

#include <functional>

#include <iostream>

using namespace std;

int main(void)

{

// containers

vector <int> vec1, vec2;

// iterators

vector <int>::iterator Iter1, Iter2;

int i;

// push data

for(i = 0; i <= 10; i++)

vec1.push_back(i);

// operate and print data

cout<<"Operation: random_shuffle(vec1.begin(), vec1.end())"<<endl;

random_shuffle(vec1.begin(), vec1.end());

cout<<"vec1 vector is data: ";

for(Iter1 = vec1.begin(); Iter1 != vec1.end(); Iter1++)

cout<<*Iter1<<" ";

cout<<endl;

// make vec1 a heap with default less than ordering

cout<<"\nOperation: make_heap(vec1.begin(), vec1.end())"<<endl;

make_heap(vec1.begin(), vec1.end());

cout<<"The heaped version of vec1 vector data: ";

for(Iter1 = vec1.begin(); Iter1 != vec1.end(); Iter1++)

cout<<*Iter1<<" ";

cout<<endl;

// make vec1 a heap with greater than ordering

cout<<"\nOperation: make_heap(vec1.begin(), vec1.end(), greater<int>())"<<endl;

make_heap(vec1.begin(), vec1.end(), greater<int>());

cout<<"The greater-than heaped version of vec1 vector data: ";

for(Iter1 = vec1.begin(); Iter1 != vec1.end(); Iter1++)

cout<<*Iter1<<" ";

cout<<endl;

return 0;

}

Output examples:

Operation: random_shuffle(vec1.begin(), vec1.end())

vec1 vector is data: 10 1 9 2 0 5 7 3 4 6 8

Operation: make_heap(vec1.begin(), vec1.end())

The heaped version of vec1 vector data: 10 8 9 4 6 5 7 3 2 1 0

Operation: make_heap(vec1.begin(), vec1.end(), greater<int>())

The greater-than heaped version of vec1 vector data: 0 1 5 2 6 9 7 3 4 8 10

Press any key to continue . . .