While refering to standard is fine, understanding it can sometimes be quite hard...
Trying in simpler words:
If you want to sort elements, you need some kind of order relation that defines which of two elements shall come first ("be the smaller one"). Some data types come with a natural order, such as integral numbers, for instance: -12 < -10 - 0 - 10 < 12. std::sort
(without comparison parameter) uses this natural order to sort elements ascending.
The third parameter gives you the possibility to tell std::sort
explicitly how this order shall be defined, imagine the following:
std::vector v({12, 7, 10});
std::sort(v.begin(), v.end(), [](int x, int y){return x > y;});
Looks unnatural, doesn't it? std::sort
interprets the comparison as "less", but we implemented a "greater"! By doing so, the greater values then (as considered being "smaller") are sorted in front of smaller ones (considered being "greater"), so we have achieved sorting in descending order...
So the comparison parameter passed to std::sort
is used to either sort differently to what the natural order would be or to define explicitly an order for data types where such order does not exist.
Side note: The order relation does not necessarily have to be a total order; however, equivalent elements then can be sorted in arbitrary order (you could, though, use std::stable_sort
instead to at least preserve their relative order before sorting):
int a[12, 7, 10, 7];
std::vector<int*> v({&a[0], &a[1], &a[2], &a[3]});
std::sort(v.begin(), v.end(), [](int* x, int* y) { return *x < *y; });
// v[2] == &a[2]
// v[3] == &a[1]
// BUT:
// v[0] == &a[1] && v[1] == &a[3] || v[0] == &a[3] && v[1] == &a[1]