Illustrating the generic nth_element algorithm : nth_element « STL Algorithms Sorting « C++ Tutorial






#include <iostream>
#include <cassert>
#include <algorithm>
#include <vector>
using namespace std;

int main()
{
  vector<int> v(7);

  v[0] = 25; 
  v[1] = 7; 
  v[2] = 9;
  v[3] = 2; 
  v[4] = 0; 
  v[5] = 5; 
  v[6] = 21;

  const int N = 4;

  // Use nth_element to place the Nth smallest 
  // element in v in the Nth position, v.begin() + N:

  nth_element(v.begin(), v.begin() + N, v.end());
  
  for (int i = 0; i < N; ++i)
    assert (v[N] >= v[i]);
  
  for (int i = N + 1; i < 7; ++i)
     cout << v[N];

  return 0;
}
99








27.7.nth_element
27.7.1.Illustrating the generic nth_element algorithm
27.7.2.Use nth_element to extract the four lowest elements
27.7.3.Use nth_element to extract the four highest elements
27.7.4.Use nth_element with custom function to extract the four highest elements