std::sort
std::sort rearranges a random-access range into non-decreasing order. It is O(n log n) and not stable: equal elements may change relative order. Pass a comparator to sort by something other than operator<.
Detailed Explanation
You have a vector of scores and you want them descending. std::sort(v.begin(), v.end(), std::greater<int>{}); does it. The algorithm needs random-access iterators, so it works on vector, array, deque, and pointers into a C array. It does not compile on list; call lst.sort().
Typical implementations are introsort: quicksort that switches to heapsort if recursion goes too deep, and to insertion sort on small partitions. Average and worst case are O(n log n). Extra memory is O(log n) stack. That is why sort is the default and stable_sort is the one you opt into when you need stability and can pay for it.
The comparator must define a strict weak ordering. less is the default. [](int a, int b) { return a <= b; } is not strict (equal elements compare true) and is undefined behaviour. The comparator should not modify the elements. Equal elements are those for which !comp(a, b) && !comp(b, a).
C++20 std::ranges::sort(v) takes the container. A projection sorts by a member: std::ranges::sort(users, {}, &User::id). A custom order: std::ranges::sort(users, std::greater{}, &User::id).
sort is not qsort. qsort takes a function pointer, cannot inline the compare, and is not typesafe. std::sort instantiates on the iterator and comparator types and inlines the comparison. That is why it beats qsort on the same data.
When not to use it: the range is already almost sorted and you care about stability (stable_sort or inplace_merge). You only need the k smallest (nth_element or partial_sort). You need a running median (a different structure). You have a list.
Sorting pointers sorts the pointers, not the objects. Sorting string_views sorts the views' characters (lexicographic) but does not keep the owners alive. Sorting a vector<bool> works and is still a special case; prefer vector<char>.
After sort, binary_search and lower_bound are legal. Before sort, they are meaningless.
Code Examples
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> v{3, 1, 4, 1, 5};
std::sort(v.begin(), v.end());
for (int n : v) std::cout << n << ' ';
std::cout << '\n'; // prints: 1 1 3 4 5
std::sort(v.begin(), v.end(), std::greater<int>{});
std::cout << v.front() << '\n'; // prints: 5
}#include <algorithm>
#include <iostream>
#include <ranges>
#include <string>
#include <vector>
struct User { std::string name; int id; };
int main() {
std::vector<User> users{{"al", 2}, {"ada", 1}};
std::ranges::sort(users, {}, &User::id);
std::cout << users[0].name << '\n'; // prints: ada
}Common Gotchas
A non-strict comparator is undefined behaviour
`return a <= b;` can crash or loop inside `sort`. Use `<`.
`sort` is not stable
two records with the same key may swap. Use `stable_sort` if you already ordered by a secondary key.