std::is_sorted in C++: Troubleshooting and Alternatives

2025-09-19

std::is_sorted is a C++ standard library function from the <algorithm> header. It's a simple, yet powerful, tool for checking if a range of elements is sorted. It returns true if the elements are in non-decreasing order (e.g., 1, 2, 2, 3) and false otherwise. It can be used with various data structures like std::vector, std::list, or even C-style arrays.

The basic syntax looks like this

template <class ForwardIterator>
  bool is_sorted (ForwardIterator first, ForwardIterator last);

You just provide a pair of iterators that define the beginning and end of the range you want to check.

This is a classic C++ mistake. When you use iterators to define a range, you need to remember that the end iterator points to one element past the last element you want to include.

Problematic Code
Let's say you have a std::vector of size 5 and you try to check from myVec.begin() to myVec.begin() + 4. This only checks the first four elements and misses the last one.

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 0};
    // Incorrect: This checks only the first 4 elements
    if (std::is_sorted(numbers.begin(), numbers.begin() + 4)) {
        std::cout << "The first 4 elements are sorted." << std::endl;
    } else {
        std::cout << "The first 4 elements are NOT sorted." << std::endl;
    }
    return 0;
}

Corrected Code
To check the entire vector, you should use myVec.begin() and myVec.end().

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 0};
    // Correct: This checks the entire vector
    if (std::is_sorted(numbers.begin(), numbers.end())) {
        std::cout << "The vector is sorted." << std::endl;
    } else {
        std::cout << "The vector is NOT sorted." << std::endl;
    }
    return 0;
}

By default, std::is_sorted uses the < operator to compare elements. If you're working with a custom class or struct, it won't know how to compare them unless you provide a custom comparison function.

Problematic Code

#include <iostream>
#include <vector>
#include <algorithm>

struct Point {
    int x, y;
};

int main() {
    std::vector<Point> points = {{1, 2}, {3, 4}};
    // This will result in a compilation error because Point doesn't have an operator<
    // if (std::is_sorted(points.begin(), points.end())) {
    //     ...
    // }
    return 0;
}

Corrected Code
You can provide a lambda function as a custom comparator. This is a super flexible and modern C++ approach!

#include <iostream>
#include <vector>
#include <algorithm>

struct Point {
    int x, y;
};

int main() {
    std::vector<Point> points = {{1, 2}, {2, 1}, {3, 4}};
    // Correct: Provide a custom comparison using a lambda
    auto compare_points = [](const Point& a, const Point& b) {
        return a.x < b.x; // Sorts based on the x-coordinate
    };

    if (std::is_sorted(points.begin(), points.end(), compare_points)) {
        std::cout << "The points are sorted by x-coordinate." << std::endl;
    } else {
        std::cout << "The points are NOT sorted by x-coordinate." << std::endl;
    }

    return 0;
}

Sometimes, std::is_sorted isn't quite what you need, or you just want to do it yourself to learn.

This is the most straightforward and fundamental alternative. You can write a simple for loop to check if each element is less than or equal to the next one. This method is great for learning the basics and for cases where you need more fine-grained control or want to perform another action inside the loop.

Sample Code

#include <iostream>
#include <vector>

template <typename T>
bool is_sorted_manual(const std::vector<T>& vec) {
    if (vec.size() < 2) {
        return true; // A single-element or empty vector is always sorted!
    }
    for (size_t i = 0; i < vec.size() - 1; ++i) {
        if (vec[i] > vec[i+1]) {
            return false;
        }
    }
    return true;
}

int main() {
    std::vector<int> my_vec = {1, 2, 3, 4, 5};
    if (is_sorted_manual(my_vec)) {
        std::cout << "Vector is sorted (manual check)." << std::endl;
    } else {
        std::cout << "Vector is not sorted (manual check)." << std::endl;
    }
    return 0;
}

Why use this?

Learning
It helps you understand the underlying logic.

Control
You can easily add other checks or actions within the loop.

This is a less-known but very useful function, also in the <algorithm> header. It returns an iterator to the first element that is not in a sorted position. If the entire range is sorted, it returns the last iterator. This is great for finding the "problem spot" in your data.

Sample Code

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> numbers = {1, 2, 5, 4, 6};
    auto unsorted_it = std::is_sorted_until(numbers.begin(), numbers.end());

    if (unsorted_it != numbers.end()) {
        std::cout << "The vector is not fully sorted. The first unsorted element is: " << *unsorted_it << std::endl;
    } else {
        std::cout << "The entire vector is sorted." << std::endl;
    }
    return 0;
}

Why use this?

Debugging
It helps you pinpoint exactly where a sequence stops being sorted.


cpp



The Right Way to Reset Random Distributions in C++

The std::cauchy_distribution is a class in the C++ Standard Library, found in the <random> header. It's used to generate pseudo-random numbers that follow a Cauchy distribution


The C++ try_lock_shared Function: When to Use It and What to Do Instead

The try_lock_shared function is a non-blocking way to acquire a shared lock. This means if the lock isn't available, the function returns immediately instead of waiting


A Guide to C++'s std::piecewise_constant_distribution and its reset() Method

Hey there! Let's talk about the std::piecewise_constant_distribution::reset() method in C++. This function is used to reset the internal state of a piecewise constant distribution



A Guide to Handling std::chrono::hh_mm_ss Constructor Pitfalls

One of the most frequent issues with the hh_mm_ss constructor is dealing with out-of-range values. The constructor is quite strict


Mastering C++ std::nested_exception: A Practical Guide

Imagine you're running some code, and a function throws an exception. But inside the catch block for that exception, your cleanup code also fails and throws a different exception


The Monotonic Buffer: C++ Dynamic Memory Management Explained

Hello there! Let's dive into the fascinating world of C++ dynamic memory management, specifically focusing on std::pmr::monotonic_buffer_resource::monotonic_buffer_resource


Boost Your C++ Skills: A Deep Dive into std::front_inserter and its Best Practices

Think of an iterator like a pointer that moves through a container. std::front_inserter is a special kind of iterator adapter


C++ I/O Error Handling: A Guide to std::basic_ios::fail()

Hey there! Let's talk about std::basic_ios::fail in C++. It's a really useful function for checking if an input/output (I/O) operation has gone wrong


Mastering C++ I/O: A Guide to Stream Synchronization and Alternatives

std::basic_filebuf::sync() is a member function that synchronizes the internal buffer with the associated external device


C++ Named Requirements: TrivialClock Explained

A TrivialClock is a clock that meets a specific set of criteria. Basically, it's a clock that is guaranteed to be monotonic (it never goes backward) and stable (the time between ticks is constant and not affected by external factors like system time changes). This reliability makes it suitable for measuring elapsed time with high precision