Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++
sort
communitycreator

How to use the is_sorted() function in C++

Harsh Jain

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.

Syntax

bool is_sorted(ForwardIterator first, ForwardIterator last)

Parameters

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.

Return

The is_sorted() function returns a Boolean value that specifes whether the elements in the range [first, last) are sorted or not.

Code

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";
  else
    cout << "Not sorted";
  return 0;
}
Use is_sorted() function in C++

Explanation

  • From lines 1 to 3, we import the required header files.
  • In line 7, we create a vector that contains some integer elements.
  • In line 8, we call the is_sorted() function and pass the required parameters.
  • In line 9, we print if the vector is sorted.
  • Otherwise, in line 11, we print that the vector is not sorted.

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";
  else
    cout << "Not sorted in Reverse order";
  return 0;
}
Use is_sorted() function in C++

Explanation

  • From lines 6 to 8, we create a function that accepts two integers and returns 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.
  • In line 12, we pass the function pointer to the 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.

RELATED TAGS

c++
sort
communitycreator
RELATED COURSES

View all Courses

Keep Exploring