What is the nth_element() function in C++?

The nth_element() function rearranges elements and works in such a way that the position of the nthn^{th} element remains unchanged. The elements preceding the nthn^{th} element must be less than elements succeeding it.

Syntax

nth_element(Begin, nth, End, Pred);

Parameter

The nth_element() function accepts the following parameters:

  • Begin: The iterator pointing to the first element in the range from first till nthn^{th} element.

  • nth: The iterator pointing to address from the range of first to last .

  • End: The iterator pointing to the last element in the range from nthn^{th} till last element.

  • Pred: A user defined binary function which returns true if the two arguments passed are in order (follows strict weak ordering).

Return value

The function doesn’t return anything.

Code

Let’s have a look at the code.

#include <iostream>
#include <algorithm>
using namespace std;
bool comp(int x, int y)
{
return (x < y);
}
int main()
{
int arr[] = { 13, 21, 110, 15, 32, 65, 34, 47 };
nth_element(arr, arr + 4, arr + 8, comp);
for (int i = 0; i < 8; i++)
cout << arr[i] << " ";
return 0;
}

Explanation

  • In lines 1 to 2, we imported the required libraries.

  • In line 4, we defined a binary function to check whether the first argument is less than the second argument. (We are going to use this function as a parameter to nth_element() function).

  • In line 8, we made a main() function.

  • In line 10, we initialize an array.

  • In line 12, we used the nth_element() function to fix the fourth element and it also rearranges the array in such a way that elements preceding the fourth element are less than the elements succeeding it.

  • In line 13, we used a loop to access and display the elements of the array after using nth_element() function on array.

In this way, we can use the nth_element() function in C++.