Mega Code Archive

 
Categories / C++ Tutorial / STL Algorithms Heap
 

Demonstrating push_heap, pop_heap, make_heap and sort_heap

#include <iostream> #include <algorithm> #include <vector> using namespace std; int main(){    const int SIZE = 10;    int a[ SIZE ] = { 3, 100, 52, 77, 22, 31, 1, 98, 13, 40 };    int i;    vector< int > v( a, a + SIZE ), v2;    make_heap( v.begin(), v.end() );    sort_heap( v.begin(), v.end() );    for ( i = 0; i < SIZE; ++i ) {       v2.push_back( a[ i ] );       push_heap( v2.begin(), v2.end() );          }        for ( i = 0; i < v2.size(); ++i ) {       cout << "\nv2 after " << v2[ 0 ] << " popped from heap\n";       pop_heap( v2.begin(), v2.end() - i );    }    cout << endl;    return 0; }