CHAPTER11-28.cpp
上传用户:fjc899
上传日期:2007-07-03
资源大小:187k
文件大小:2k
源码类别:

STL

开发平台:

C/C++

  1. //文件名:CHAPTER11-28.cpp
  2. #include <vector>
  3. #include <algorithm>
  4. #include <functional>      // For greater<int>( )
  5. #include <iostream>
  6. // Return whether first element is greater than the second
  7. bool UDgreater ( int elem1, int elem2 )
  8. {   return elem1 > elem2;}
  9. int main( )
  10. {
  11.    using namespace std;
  12.    vector <int> v1;
  13.    vector <int>::iterator Iter1;
  14.    for (int i = 0 ; i <= 5 ; i++ ) {v1.push_back( 3 * i );   }
  15.    for (int ii = 0 ; ii <= 5 ; ii++ ) {v1.push_back( 3 * ii + 1 );   }
  16.    for (int iii = 0 ; iii <= 5 ; iii++ ) {v1.push_back( 3 * iii +2 );   }
  17.    cout << "Original vector:n v1 = ( " ;
  18.    for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ ) cout << *Iter1 << " ";
  19.    cout << ")" << endl;
  20.    nth_element(v1.begin( ), v1.begin( ) + 3, v1.end( ) );
  21.    cout << "Position 3 partitioned vector:n v1 = ( " ;
  22.    for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ ) cout << *Iter1 << " ";
  23.    cout << ")" << endl;
  24.    // To sort in descending order, specify binary predicate
  25.    nth_element( v1.begin( ), v1.begin( ) + 4, v1.end( ),greater<int>( ) );
  26.    cout << "Position 4 partitioned (greater) vector:n v1 = ( " ;
  27.    for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ ) cout << *Iter1 << " ";
  28.    cout << ")" << endl;
  29.    random_shuffle( v1.begin( ), v1.end( ) );
  30.    cout << "Shuffled vector:n v1 = ( " ;
  31.    for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ ) cout << *Iter1 << " ";
  32.    cout << ")" << endl;
  33.    // A user-defined (UD) binary predicate can also be used
  34.    nth_element( v1.begin( ), v1.begin( ) + 5, v1.end( ), UDgreater );
  35.    cout << "Position 5 partitioned (UDgreater) vector:n v1 = ( " ;
  36.    for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )    cout << *Iter1 << " ";
  37.    cout << ")" << endl;
  38. }