CKTIS / C++
std::ranges::sort — sorting a range with a projection
std::ranges::sort from <algorithm> sorts elements within an existing range. It accepts a whole range or an iterator and sentinel, plus an optional comparator and key projection.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
std::ranges::sort(r);
std::ranges::sort(r, comp);
std::ranges::sort(r, comp, proj);
std::ranges::sort(first, last);
std::ranges::sort(first, last, comp);
std::ranges::sort(first, last, comp, proj);std::ranges::sort from <algorithm> rearranges elements within an existing range; it does not create a sorted copy or a lazy view. Pass either a whole range r or a first, last pair describing the half-open range [first, last).
Random access and satisfaction of the sortable constraint are required: elements must support rearrangement and comparison. The iterator overload allows different iterator and sentinel types. The default comparator is std::ranges::less, and the default projection is std::identity. A projection such as &Item::score selects the comparison key, but entire elements are moved. The comparator must define a strict weak ordering; do not use <= instead of <.
Sorting is not stable: the order of elements with equivalent keys is not guaranteed. For N elements, it performs O(N log N) comparisons and projection applications. The iterator overload returns the end iterator. The range overload returns std::ranges::borrowed_iterator_t<R>: the end iterator for a borrowed range, including an lvalue argument, or std::ranges::dangling for a non-borrowed temporary range.
The example sorts by score; {} retains the default comparator. Distinct keys make the result unambiguous. This entry targets C++23; the current working draft may include later extensions. The repository compiler flag does not attest the production runtime. The displayed code was run unchanged in an isolated environment. Its standard output matched the stated output exactly.
Examples
#include <algorithm>
#include <array>
#include <iostream>
struct Item {
int id;
int score;
};
int main() {
std::array<Item, 3> items{{{1, 30}, {2, 10}, {3, 20}}};
std::ranges::sort(items, {}, &Item::score);
for (const auto& item : items) {
std::cout << item.id << ':' << item.score << '\n';
}
}
Result
2:10 3:20 1:30
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.