From Beginner to Pro: Your Guide to std::is_sorted_until in C++

2025-09-23

std::is_sorted_until is generally pretty straightforward, but a few common pitfalls can trip up new programmers. Let's look at some of them and how to fix them.

A frequent issue is passing iterators from different containers or an invalid range. For example, passing my_vector.begin() and my_list.end() will lead to undefined behavior.

The Problem

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

int main() {
    std::vector<int> my_vector = {1, 2, 3, 5, 4};
    std::list<int> my_list = {10, 20, 30};

    // This is a big no-no!
    auto it = std::is_sorted_until(my_vector.begin(), my_list.end());

    if (it != my_vector.end()) {
        std::cout << "The sequence is not sorted at element: " << *it << std::endl;
    }
    return 0;
}

The Fix

Always ensure your start and end iterators belong to the same container and define a valid range within it.

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

int main() {
    std::vector<int> my_vector = {1, 2, 3, 5, 4};

    // Correctly using iterators from the same vector
    auto it = std::is_sorted_until(my_vector.begin(), my_vector.end());

    if (it != my_vector.end()) {
        std::cout << "The sequence stops being sorted at the element with value: " << *it << std::endl;
    } else {
        std::cout << "The entire sequence is sorted." << std::endl;
    }
    return 0;
}

By default, std::is_sorted_until uses operator< to determine the sort order. If you're working with custom objects or need a different sorting logic (like descending order), you must provide a custom comparator.

The Problem

You want to check for a descending sequence but don't provide a comparator. The function will use the default operator< and likely fail.

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

int main() {
    std::vector<int> my_vector = {5, 4, 3, 2, 1};

    // This will say it's not sorted because it's checking for ascending order
    auto it = std::is_sorted_until(my_vector.begin(), my_vector.end());

    if (it != my_vector.end()) {
        std::cout << "The sequence is not sorted (in ascending order) at element: " << *it << std::endl;
    }
    return 0;
}

The Fix

Pass a custom lambda function or a function object as the third argument to specify your sorting criteria. A great choice for descending order is std::greater<T>.

#include <iostream>
#include <vector>
#include <algorithm>
#include <functional> // For std::greater

int main() {
    std::vector<int> my_vector = {5, 4, 3, 2, 1};

    // Correctly checking for a descending sequence using std::greater
    auto it = std::is_sorted_until(my_vector.begin(), my_vector.end(), std::greater<int>());

    if (it != my_vector.end()) {
        std::cout << "The sequence is not sorted (in descending order) at element: " << *it << std::endl;
    } else {
        std::cout << "The entire sequence is sorted in descending order!" << std::endl;
    }
    return 0;
}

While std::is_sorted_until is the most efficient and idiomatic way to find the sorted prefix of a sequence, you can also achieve similar results with other methods, although they may be less performant or more verbose.

You can write your own simple loop to iterate through the container and check if each element is less than the next one. This gives you complete control but can be error-prone and less expressive than the standard library function.

Example

#include <iostream>
#include <vector>

// Manual implementation of is_sorted_until
template <typename ForwardIt>
ForwardIt custom_is_sorted_until(ForwardIt first, ForwardIt last) {
    if (first == last) {
        return last;
    }

    ForwardIt next = first;
    while (++next != last) {
        if (*next < *first) {
            return next;
        }
        first = next;
    }
    return last;
}

int main() {
    std::vector<int> my_vector = {1, 2, 3, 5, 4};
    auto it = custom_is_sorted_until(my_vector.begin(), my_vector.end());

    if (it != my_vector.end()) {
        std::cout << "Found a break in the sort at element: " << *it << std::endl;
    }
    return 0;
}

std::adjacent_find finds the first pair of adjacent elements for which a specific condition is met. You can use it with a custom lambda to check for an unsorted pair.

Example

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

int main() {
    std::vector<int> my_vector = {1, 2, 3, 5, 4};

    // Find the first adjacent pair where the second element is smaller than the first
    auto it = std::adjacent_find(my_vector.begin(), my_vector.end(),
        [](int a, int b) {
            return a > b;
        });

    if (it != my_vector.end()) {
        std::cout << "The sequence is not sorted at element: " << *(it + 1) << std::endl;
    }
    return 0;
}

cpp



Mastering C++ std::array: Common Pitfalls and Smarter Alternatives

Fixed Size at Compile Time One of the most common "gotchas" with stdarray is its fixed size. You must specify the size of the array at compile time


Mastering C++ Metaprogramming: Common Issues with std::is_pointer_interconvertible_with_class and Modern Alternatives

This trait, found in the <type_traits> header, is used to check if a pointer to an object can be safely converted to a pointer to another type within the same class hierarchy


A Developer's Guide to recursive_directory_iterator in C++

The C++ Filesystem library, particularly the std::filesystem::recursive_directory_iterator, provides a powerful and convenient way to traverse a directory and all its subdirectories



Here are a few title options for the previous explanation, formatted as requested.

The most common issues developers face with steady_clock are often related to misunderstanding its purpose or incorrectly using the timing results


The Virtual Role of std::basic_istream's Destructor in C++ I/O

Since std::basic_istream is a base class (like the foundation for std::ifstream for files or std::istringstream for strings), its destructor's primary role is very specific and designed to support its derived classes


Mastering C++ Ranges: zip_transform_view::iterator

The operators for std::ranges::zip_transform_view::iterator are what let you move through the elements of the view and access the transformed values


C++ I/O Troubleshooting: Solving Common Problems with `` and Stream States

While it's a powerful tool, you might run into a few common issues when working with C++ I/O streams.This usually happens when there's an error flag set on the stream


Fixing "tolower" Errors with C++ Strings

The core issue is that std::tolower is designed to work on a single character, specifically an int representation of a character


C++ Concurrency: A Guide to std::atomic_ref::wait and Its Pitfalls

std::atomic_ref::wait is a C++ concurrency feature that lets a thread block (or "wait") until an atomic variable changes its value


C++ Regex Troubleshooting: A Friendly Guide to std::sub_match

When you perform a regex search in C++, the std::match_results object stores the results. Each successful capture group within that result is represented by a std::sub_match object