![]() |
VOOZH | about |
In C++, is_sorted() is a built-in function used to check whether the elements in the given range are sorted or not in ascending order by default. You can also provide a custom comparator to check for descending order or any other sorting criteria.
For example: Let's create a vector and check if the elements are sorted using is_sorted() method.
Sorted
is_sorted() is defined inside <algorithm> header file.
is_sorted(first, last, comp);
Parameters:
Return Value: Returns true, if the range is sorted otherwise it returns false.
The following examples demonstrates the use of is_sorted() method in different scenario:
Given Array is Sorted
We can check if a given vector or array is sorted within a specified range.
Sorted
Explanation: is_sorted(v.begin()+2, v.end()) check if the vector is sorted from index '2' till the end.
Given Vector is Sorted
Given Vector is Sorted
Not Sorted
Explanation: The set is already sorted in ascending order. We have used is_sorted() with custom comparator to check if the set is in descending order.