The is_sorted()
function is available in the <algorithm.h>
header file in C++. This function helps determine whether the elements in the specified range are sorted or not.
bool is_sorted(ForwardIterator first, ForwardIterator last)
The is_sorted()
function accepts the following parameters.
first
: This is the start position of your search space. It is an iterator that usually points to the start of an array.
last
: This is the end position of your search space. It is an iterator that usually points to the last position of an array.
comparator
: This is an optional parameter. It is a binary function that accepts two elements of the same type as you have in your list. It then returns a Boolean value that indicates which element to be considered first among the two elements passed to the function.
The is_sorted()
function returns a Boolean value that specifes whether the elements in the range [first, last) are sorted or not.
Let’s look at the code now.
#include <iostream>#include <algorithm>#include <vector>using namespace std;int main() {vector<int> vec = {1,2,5,68,99,34};if(is_sorted(vec.begin(), vec.end()))cout << "Sorted";elsecout << "Not sorted";return 0;}
is_sorted()
function and pass the required parameters.Let’s now see how to use the comparator
function in the code snippet below.
#include <iostream>#include <algorithm>#include <vector>using namespace std;bool reverse_order(int a, int b){return a > b;}int main() {vector<int> vec = {99,45,21,11,2,1};if(is_sorted(vec.begin(), vec.end(), reverse_order))cout << "Sorted in Reverse order";elsecout << "Not sorted in Reverse order";return 0;}
true
if the first integer is greater than the second. We will use this function to check whether the array is sorted in reverse order, i.e., in the decreasing order.is_sorted()
function to check for the decreasing order. Then, we print the result accordingly.In this way, we can use the comparator function to check whether the array is sorted or not based on some conditions.