STL_Algorithm: heap

#include <iostream>

#include <algorithm>

#include <vector>

#include <iterator>

 

using std::cout;

using std::endl;

 

int main()

{

    const int SIZE = 10;

    int a[ SIZE ] = { 3, 100, 52, 77, 22, 31, 1, 98, 13, 40 };

    std::vector< int > v( a, a + SIZE ), v2;

    std::ostream_iterator< int > outputIt( cout, " " );

 

    cout<<"Vector v before make_heap:/n";

    std::copy( v.begin(), v.end(), outputIt );

 

    std::make_heap( v.begin(), v.end() );

 

    cout<<"/nVector v after make_heap:/n";

    std::copy( v.begin(), v.end(), outputIt );

 

    std::sort_heap( v.begin(), v.end() );

 

    cout<<"/nVector v after sort_heap:/n";

    std::copy( v.begin(), v.end(), outputIt );

 

    cout<<"/n/nArray a contains: ";

    std::copy( a, a + SIZE, outputIt );

 

    cout<< endl;

    for( int i = 0; i< SIZE; ++i )

    {

        v2.push_back( a[i] );

        std::push_heap( v2.begin(), v2.end() );

        cout<<"/nv2 after push_heap(a["<<i<<"]): ";

        std::copy( v2.begin(), v2.end(), outputIt );

    }

 

    cout<<endl;

 

    for( int j = 0; j<v2.size(); ++j )

    {

        cout<<"/nv2 after "<<v2[0]<<" popped from heap/n";

        std::pop_heap( v2.begin(), v2.end() - j );

        std::copy( v2.begin(), v2.end(), outputIt );

    }

 

    cout<<endl;

 

    return 0;

 

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章