nth_element 使用小例

#include <vector>
#include <algorithm>
#include <functional>      // For greater<int>( )
#include <iostream>
using namespace std;
// Return whether first element is greater than the second
struct MoreThan: public binary_function<int,int,bool> {
 bool operator()(const int& a1,const int& a2) const {return a1 > a2;}
};ios

// bool UDgreater (const int elem1,const int elem2 )
// {
//  return elem1 > elem2;
// }dom

int main( )
{
 using namespace std;
 vector <int> v1;
 vector <int>::iterator Iter1;spa

 int i;
 for ( i = 0 ; i <= 5 ; i++ )
 {
  v1.push_back( 3 * i );
 }ci

 int ii;
 for ( ii = 0 ; ii <= 5 ; ii++ )
 {
  v1.push_back( 3 * ii + 1 );
 }element

 int iii;
 for ( iii = 0 ; iii <= 5 ; iii++ )
 {
  v1.push_back( 3 * iii +2 );
 }it

 cout << "Original vector:\n v1 = ( " ;
 for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
  cout << *Iter1 << " ";
 cout << ")" << endl;io

 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;
 cout << "Position 3 Value is " << v1.at(3) <<endl;function

 // 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;
 cout << "Position 4 Value is " << v1.at(4) <<endl;stream

 random_shuffle( v1.begin( ), v1.end( ) );
 cout << "Shuffled vector:\n v1 = ( " ;
 for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
  cout << *Iter1 << " ";
 cout << ")" << endl;sed

 // A user-defined (UD) binary predicate can also be used
 nth_element( v1.begin( ), v1.begin( ) + v1.size()/2, v1.end( ), MoreThan());
 cout << "Position 5 partitioned (UDgreater) vector:\n v1 = ( " ;
 for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
  cout << *Iter1 << " ";
 cout << ")" << endl;

 cout << "mid Position Value is " <<  v1.at(v1.size()/2) <<endl;

 system("pause");  return 0; }

相關文章
相關標籤/搜索