Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::sort: ordering a range

std::sort, declared in algorithm, rearranges elements of a range. It requires random-access iterators and a comparison that establishes a strict weak ordering.

Version: C++23

Syntax

std::sort(values.begin(), values.end());

std::sort(values.begin(), values.end()) sorts existing elements in place rather than creating another collection. The range [first, last) stops before the position last. The end() iterator points past the final element, so this call sorts the whole vector, including its final element. Iterators must describe a valid range, and elements must meet move and swap requirements. A vector is suitable; std::list has its own sorting member.

The comparator returns true when the first element should precede the second. Descending order can use a > b. Do not use a <= b: it returns true for equal values, violating strictness. The criterion must be consistent and transitive; do not modify compared values during comparison.

Ordinary std::sort does not guarantee preservation of the order of elements equivalent under the comparator. If you need that guarantee, consider std::stable_sort. The comparison count is O(N log N); the cost of each comparison depends on the data. The example uses distinct integers, so both displayed orders are unambiguous. For data containing NaN, ordinary floating-point comparisons may fail the required ordering.

Examples

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

int main() {
    std::vector<int> values{3, 1, 2};
    std::sort(values.begin(), values.end());
    for (int value : values) std::cout << value;
    std::cout << '\n';
    std::sort(values.begin(), values.end(), [](int a, int b) { return a > b; });
    for (int value : values) std::cout << value;
    std::cout << '\n';
}

Result

123
321

Sources