++


nth_element()


template < class RandomAccessIterator >

void

nth_element( RandomAccessIterator first,

RandomAccessIterator nth,

RandomAccessIterator last );

 

template < class RandomAccessIterator, class Compare >

void

nth_element( RandomAccessIterator first,

RandomAccessIterator nth,

RandomAccessIterator last, Compare comp );

nth_element() , [first,last), , , nth, ,   . ,

int ia[] = {29,23,20,22,17,15,26,51,19,12,35,40};

nth_element(), nth ( 26):

nth_element( &ia[0], &ia[6], &ia[2] );

, , 26, 26, , 26, :

{23,20,22,17,15,19,12,26,51,35,40,29}

, , nth, . , ,   , .

#include <algorithm>

#include <vector>

#include <iostream.h>

/* :

: 29 23 20 22 17 15 26 51 19 12 35 40

, 26

12 15 17 19 20 22 23 26 51 29 35 40

, 23

40 35 29 51 26 23 22 20 19 17 15 12

*/

 

int main()

{

int ia[] = {29,23,20,22,17,15,26,51,19,12,35,40};

vector< int,allocator > vec( ia, ia+12 );

ostream_iterator<int> out( cout," " );

 

cout << " : ";

copy( vec.begin(), vec.end(), out ); cout << endl;

cout << ", "

<< *( vec.begin()+6 ) << endl;

nth_element( vec.begin(), vec.begin()+6, vec.end() );

copy( vec.begin(), vec.end(), out ); cout << endl;

cout << " , "

<< " "

<< *( vec.begin()+6 ) << endl;

nth_element( vec.begin(), vec.begin()+6,

vec.end(), greater<int>() );

copy( vec.begin(), vec.end(), out ); cout << endl;

}




- -  - -  - -