std::is_sorted_until

Header: <algorithm>

Examines the range [first,last) and finds the largest range beginning at first in which the elements are sorted in non-descending order.

# Declarations

template< class ForwardIt >
ForwardIt is_sorted_until( ForwardIt first, ForwardIt last );

(since C++11) (constexpr since C++20)

template< class ExecutionPolicy, class ForwardIt >
ForwardIt is_sorted_until( ExecutionPolicy&& policy,
ForwardIt first, ForwardIt last );

(since C++17)

template< class ForwardIt, class Compare >
ForwardIt is_sorted_until( ForwardIt first, ForwardIt last,
Compare comp );

(since C++11) (constexpr since C++20)

template< class ExecutionPolicy, class ForwardIt, class Compare >
ForwardIt is_sorted_until( ExecutionPolicy&& policy,
ForwardIt first, ForwardIt last,
Compare comp );

(since C++17)

# Parameters

# Return value

The upper bound of the largest range beginning at first in which the elements are sorted in ascending order. That is, the last iterator it for which range [first,it) is sorted.

# Example

#include <algorithm>
#include <cassert>
#include <iostream>
#include <iterator>
#include <random>
#include <string>
 
int main()
{
    std::random_device rd;
    std::mt19937 g(rd());
    const int N = 6;
    int nums[N] = {3, 1, 4, 1, 5, 9};
 
    const int min_sorted_size = 4;
 
    for (int sorted_size = 0; sorted_size < min_sorted_size;)
    {
        std::shuffle(nums, nums + N, g);
        int *const sorted_end = std::is_sorted_until(nums, nums + N);
        sorted_size = std::distance(nums, sorted_end);
        assert(sorted_size >= 1);
 
        for (const auto i : nums)
            std::cout << i << ' ';
        std::cout << ": " << sorted_size << " initial sorted elements\n"
                  << std::string(sorted_size * 2 - 1, '^') << '\n';
    }
}

# See also