CHAPTER11-28.cpp
上传用户:fjc899
上传日期:2007-07-03
资源大小:187k
文件大小:2k
- //文件名:CHAPTER11-28.cpp
- #include <vector>
- #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;
- vector <int>::iterator Iter1;
- for (int i = 0 ; i <= 5 ; i++ ) {v1.push_back( 3 * i ); }
- for (int ii = 0 ; ii <= 5 ; ii++ ) {v1.push_back( 3 * ii + 1 ); }
- for (int iii = 0 ; iii <= 5 ; iii++ ) {v1.push_back( 3 * iii +2 ); }
- cout << "Original vector:n v1 = ( " ;
- for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ ) cout << *Iter1 << " ";
- cout << ")" << endl;
- nth_element(v1.begin( ), v1.begin( ) + 3, v1.end( ) );
- cout << "Position 3 partitioned vector:n v1 = ( " ;
- for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ ) cout << *Iter1 << " ";
- cout << ")" << endl;
- // To sort in descending order, specify binary predicate
- nth_element( v1.begin( ), v1.begin( ) + 4, v1.end( ),greater<int>( ) );
- cout << "Position 4 partitioned (greater) vector:n v1 = ( " ;
- for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ ) cout << *Iter1 << " ";
- cout << ")" << endl;
- random_shuffle( v1.begin( ), v1.end( ) );
- cout << "Shuffled 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
- nth_element( v1.begin( ), v1.begin( ) + 5, v1.end( ), UDgreater );
- cout << "Position 5 partitioned (UDgreater) vector:n v1 = ( " ;
- for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ ) cout << *Iter1 << " ";
- cout << ")" << endl;
- }