Mega Code Archive

 
Categories / C++ / Algorithm
 

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