C++ STL algorithm, sort_heap() code 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 sort_heap() to convert a heap into a sorted range in C++ programming

To show: How to use the C++ algorithm, sort_heap() member to convert a heap into a sorted range in C++ programming

// C++ STL algorithm, sort_heap()

// compiled with /EHsc flag

#include <vector>

#include <algorithm>

#include <functional>

#include <iostream>

using namespace std;

int main(void)

{

// vector container

vector <int> vec1;

// vector iterator

vector <int>::iterator Iter1, Iter2;

int i = 0;

// push data into the vector container

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

vec1.push_back(i);

// print the data

cout<<"Original vec1 vector data: ";

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

cout<<*Iter1<<" ";

cout<<endl;

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

cout<<"\nRandom shuffle vec1 vector data: ";

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

cout<<*Iter1<<" ";

cout<<endl;

// make vec1 a heap with default less-than ordering

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

cout<<"\nThe default less-than heaped version of vec1 vector data: ";

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

cout<<*Iter1<<" ";

cout<<endl;

// note: without default less-than ordering make_heap() called, the following

// sort_heap() default less-than ordering will generate invalid heap error but it

// is OK for sort_heap() with greater than ordering...BUG???

//

// sort heap vec1 with default less-than ordering

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

cout<<"\nThe sorted heap vec1 vector data: ";

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

cout<<*Iter1<<" ";

cout<<endl;

// make vec1 a heap with greater than ordering

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

cout<<"\nThe greater than heaped version of vec1 vector data: ";

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

cout<<*Iter1<<" ";

cout<<endl;

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

cout<<"\nThe greater than sorted heap vec1 vector data:";

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

cout<<*Iter1<<" ";

cout<<endl;

return 0;

}

Output examples:

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

Random shuffle vec1 vector data: 9 2 10 3 1 6 8 4 5 7

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

The sorted heap vec1 vector data: 1 2 3 4 5 6 7 8 9 10

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

The greater than sorted heap vec1 vector data:10 9 8 7 6 5 4 3 2 1

Press any key to continue . . .