What is the partial_sort() function in C++?
In this shot, we will discuss how to use the partial_sort() function in C++. It is present in the
<algorithm> library.
The partial_sort() function is used for sorting a part of the range, not the entire range.
Parameters
The partial_sort() function takes the following parameters:
Begin: This is a random access iterator pointing to the first element in the range.End: This is a random access iterator pointing to the first element in the range.Boundary: This is a random access iterator pointing to the upper boundary element in the range [Begin, End), that is used as the upper boundary for the elements to be sorted.Pred: This is a user-defined function which returnstrueif the 2 arguments passed are in order (it follows strict weak ordering).
Return
The partial_sort() function doesn’t return anything.
Code
Let’s see the code snippet below.
#include<iostream>#include<algorithm>#include<vector>using namespace std;bool pred(int x, int y){return (x<y);}int main(){vector<int> vect = { 12, 15, 9, 7, 84, 74 },v(4);vector<int>::iterator ip;partial_sort(vect.begin(), vect.begin() + 4, vect.end(), pred);cout<<"The resultant vector after using partial_sort() is: ";for (ip = vect.begin(); ip != vect.end(); ip++)cout << *ip << " ";cout<<endl;return 0;}
Explanation
- In lines 1 to 3, we import the required libraries.
- In lines 5 to 8, we define a function to check whether the first element in the argument is less than the second element in the argument.
- In line 10, we make a
mainfunction. - In line 12, we initialize a vector and declare another vector to store the copy.
- In line 13, we declare an iterator to a vector.
- In line 14, we use the
partial_sort()method to sort a subrange of the entire initialized vector. - In line 16, we display a message regarding the upcoming modified vector.
- In lines 17 and 18, we use a loop to access and display the elements with the help of an iterator of the modified vector after using the
partial_sort()function on the vector.
In this way, we can use the partial_sort() function in C++.