On this page
std::sort / std::ranges::sort
Prev: algorithm_and_ranges | Up: algorithm_and_ranges | Next: std::find_if
Rel: std::vector, Lambdas
Ref: cppreference — std::ranges::sort
Tags: #public #prog #cpp #stdlib #algorithms #tier/core
Overview
std::sort / std::ranges::sort (<algorithm>) performs an O(n log n) worst-case in-place sort (typically introsort: quicksort + heapsort fallback + insertion sort) on any random-access range.
Notes & Pitfalls
- Comparator MUST define a strict weak ordering: Returning
truefor equal elements (a <= b) causes undefined behavior / crashes! Always use<or>. - Not guaranteed stable: Use
std::stable_sortto preserve relative order of ties, andstd::ranges::sort(vec)in C++20.
Example
#include <algorithm>
#include <cassert>
#include <vector>
int main() {
std::vector<int> v{4, 1, 3, 2};
std::sort(v.begin(), v.end());
assert((v == std::vector<int>{1, 2, 3, 4}));
}
Linked from
Related notes
- tuts/cpp/stdlib/algorithm_and_ranges/find_if Linked here; links to this page; shared tags: #algorithms, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/algorithm_and_ranges Linked here; links to this page; shared tags: #algorithms, #cpp, #prog, #stdlib
- tuts/cpp/stdlib/containers/vector Linked here; shared tags: #cpp, #prog, #stdlib, #tier
- tuts/cpp/builtins/lambdas Linked here; shared tags: #cpp, #prog, #tier
- tuts/cpp/stdlib/algorithm_and_ranges/transform shared tags: #algorithms, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/algorithm_and_ranges/ranges_views shared tags: #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/concurrency/atomic shared tags: #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/concurrency/jthread shared tags: #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/concurrency/mutex_and_lock_guard shared tags: #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/concurrency/thread shared tags: #cpp, #prog, #stdlib, #tier