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
If you wish to look at all C++ Programming examples, go to C++ Programs.

advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification 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
I’m Manish - Founder and CTO at Sanfoundry. I’ve been working in tech for over 25 years, with deep focus on Linux kernel, SAN technologies, Advanced C, Full Stack and Scalable website designs.

You can connect with me on LinkedIn, watch my Youtube Masterclasses, or join my Telegram tech discussions.

If you’re in your 20s–40s and exploring new directions in your career, I also offer mentoring. Learn more here.