CHAPTER11-21.cpp
上传用户:fjc899
上传日期:2007-07-03
资源大小:187k
文件大小:3k
- //文件名:CHAPTER11-21.cpp
- #include <vector>
- #include <list>
- #include <algorithm>
- #include <functional> // For greater<int>( )
- #include <iostream>
- // Return whether first element is greater than the second
- bool UDgreater ( int elem1, int elem2 )
- { return elem1 > elem2;}
- int main( )
- {
- using namespace std;
- vector <int> v1,v2;
- vector <int>::iterator Iter1, Iter2;
- list <int> L1;
- L1.push_back( 60 );
- L1.push_back( 50 );
- L1.push_back( 20 );
- L1.push_back( 30 );
- L1.push_back( 40 );
- L1.push_back( 10 );
- int i;
- for ( i = 0 ; i <= 5 ; i++ )
- { v1.push_back( 2 * i ); }
- int ii;
- for ( ii = 0 ; ii <= 5 ; ii++ )
- { v1.push_back( 2 * ii + 1 ); }
- cout << "Original vector v1 = ( " ;
- for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
- cout << *Iter1 << " ";
- cout << ")" << endl;
- sort( v1.begin( ), v1.end( ) );
- cout << "Sorted vector v1 = ( " ;
- for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
- cout << *Iter1 << " ";
- cout << ")" << endl;
- // To sort in descending order. specify binary predicate
- sort( v1.begin( ), v1.end( ), greater<int>( ) );
- cout << "Resorted (greater) vector v1 = ( " ;
- for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
- cout << *Iter1 << " ";
- cout << ")" << endl;
- // A user-defined (UD) binary predicate can also be used
- sort( v1.begin( ), v1.end( ), UDgreater );
- cout << "Resorted (UDgreater) vector v1 = ( " ;
- for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
- cout << *Iter1 << " ";
- cout << ")" << endl;
- // To partially sort in descending order, specify binary predicate
- partial_sort(v1.begin( ), v1.begin( ) + 4, v1.end( ), greater<int>( ) );
- cout << "Partially resorted (greater) vector:n v1 = ( " ;
- for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
- cout << *Iter1 << " ";
- cout << ")" << endl;
- // A user-defined (UD) binary predicate can also be used
- partial_sort(v1.begin( ), v1.begin( ) + 8, v1.end( ),
- UDgreater );
- cout << "Partially resorted (UDgreater) vector:n v1 = ( " ;
- for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
- cout << *Iter1 << " ";
- cout << ")" << endl;
- // Copying a partially sorted copy of L1 into v2
- for ( ii = 0 ; ii <= 9 ; ii++ )
- { v2.push_back( ii ); }
- random_shuffle( v2.begin( ), v2.end( ) );
- vector <int>::iterator result2;
- result2 = partial_sort_copy (L1.begin( ), L1.end( ), v2.begin( ),
- v2.begin( ) + 6, greater<int>( ) );
- cout << "List L1 into Vector v2 = ( " ;
- for ( Iter2 = v2.begin( ) ; Iter2 != v2.end( ) ; Iter2++ )
- cout << *Iter2 << " ";
- cout << ")" << endl;
- cout << "The first v2 element one position beyond"
- << "n the last L 1 element inserted was " << *result2
- << "." << endl;
- }