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






Illustrating the generic nth_element algorithm

  
 

#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
 */
        
    
  








Related examples in the same category

1.Use nth_element to extract the four lowest elements
2.Use nth_element to extract the four highest elements
3.Use nth_element with custom function to extract the four highest elements
4.Finding the Median