nth_element() Function in C++

This C++ program demonstrates the nth_element algorithm. The function rearranges the container elements in such a way that the element at the nth position is the element that would be in that position in a sorted sequence. The other elements are left without any specific order, except that none of the elements preceding nth are greater than it and none of the elements following it are less.

Here is the source code of the C++ program which demonstrates the nth_element algorithm. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to demonstrate nth_element() algorithm
  3.  */
  4. #include <iostream>
  5. #include <vector>
  6. #include <algorithm>
  7. #include <functional>
  8.  
  9. void print(const std::vector <int>& v)
  10. {
  11.     std::vector <int>::const_iterator i;
  12.     for(i = v.begin(); i != v.end(); i++)
  13.     {
  14.         std::cout << *i << " ";
  15.     }
  16.     std::cout << std::endl;
  17. }
  18.  
  19. int main()
  20. {
  21.     std::vector<int> v;
  22.  
  23.     for (int i = 0; i < 10; i++)
  24.         v.push_back((i + 3) % 10);
  25.     std::cout << "Vector : ";
  26.     print(v);
  27.     std::nth_element(v.begin(), v.begin() + 1, v.end(), std::greater<int>());
  28.     std::cout << "Vector with 6th element at its place, std::greater<int>() as predicate.\nVector : ";
  29.     print(v);
  30.     std::nth_element(v.begin(), v.begin() + 3, v.end(), std::less<int>());
  31.     std::cout << "Vector with 4th element at its place, std::less<int>() as predicate.\nVector : " ;
  32.     print(v);
  33. }

$ a.out
Vector : 3 4 5 6 7 8 9 0 1 2 
Vector with 6th element at its place, std::greater<int>() predicate.
Vector : 9 8 7 6 3 5 4 0 1 2 
Vector with 4th element at its place, std::less<int>() predicate.
Vector : 1 0 2 3 4 5 9 6 7 8

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.