Junior — Middle
What conditions must the 'less' comparator meet for the correct operation of the std::sort algorithm?
sobes.tech AI
Answer from AI
The "less-than" comparator used in std::sort must satisfy the following conditions for the sorting to be correct:
- Transitivity: If
a < bandb < c, thena < c. - Antisymmetry: If
a < bis true, thenb < ashould be false. - Irreflexivity: For no
ashoulda < abe true.
In other words, the comparator should define a strict weak ordering. This guarantees that the sorting algorithm can correctly order the elements.
Example of a comparator for sorting a vector of integers in ascending order:
bool less(int a, int b) {
return a < b;
}
std::sort(vec.begin(), vec.end(), less);
If the comparator violates these properties, the behavior of std::sort is undefined.