CKTIS / C++
std::ranges::is_sorted — checking whether a range is sorted
std::ranges::is_sorted returns a bool indicating whether a range is ordered according to a comparator and projection. It does not sort the data; by default, it checks nondecreasing order and allows duplicates.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
#include <algorithm>
std::ranges::is_sorted(r);
std::ranges::is_sorted(r, comp);
std::ranges::is_sorted(r, comp, proj);
std::ranges::is_sorted(first, last);
std::ranges::is_sorted(first, last, comp);
std::ranges::is_sorted(first, last, comp, proj);
// Returns bool; default comp: std::ranges::less, proj: std::identity.std::ranges::is_sorted, declared in <algorithm>, checks ordering rather than rearranging elements. The defaults, std::ranges::less and std::identity, mean nondecreasing order. Equivalent elements are allowed, and an empty or single-element range produces true.
Pass either a whole range r or a pair first, last describing [first, last). The first form requires a forward_range; the second requires a forward_iterator and a compatible sentinel, which need not have the same type as the iterator. Both forms return bool and are constexpr, so suitable arguments allow compile-time evaluation.
The proj parameter selects the value to compare; it can be a pointer to a data member, such as &Item::score. The comp parameter defines the ordering of projected values. For consecutive elements previous and current, the order is violated if std::invoke(comp, std::invoke(proj, current), std::invoke(proj, previous)) yields true. The comparator must define a strict weak ordering on projected values; do not use <=. Use std::ranges::greater{} to check nonincreasing order.
The cost is linear in the number of elements. Unlike std::ranges::is_sorted_until, which identifies the end of the sorted prefix, this algorithm reports only a Boolean result. This entry covers the non-execution-policy overloads appropriate to the stated C++23 target; the current working draft also contains later extensions.
Examples
#include <algorithm>
#include <array>
#include <functional>
#include <iostream>
struct Item {
int score;
};
int main() {
const std::array<Item, 3> items{{{2}, {2}, {5}}};
std::cout << std::boolalpha;
std::cout << std::ranges::is_sorted(items, {}, &Item::score) << '\n';
std::cout << std::ranges::is_sorted(
items.begin(), items.end(), std::ranges::greater{}, &Item::score
) << '\n';
}
Result
true false
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.