C++ Sorting Crash?
Today, while sorting a vector using a comparison function in C++, I encountered a crash.
The error message was a segment fault, providing no clear indication of the exact issue in the code.
After some investigation, I finally pinpointed it, the issue was with the comparison function:
bool comp(int a, int b){ |
Using a <= b is incorrect, because it results in ambiguous comparisons.
After change it to a < b, the problem was solved.
Comparison Function Rules:
| Rule | Description | Example/Explanation |
|---|---|---|
| Asymmetry | If comp(a, b) is true, then comp(b, a) must be false. |
If a < b is true, then b < a should be false. |
| Transitivity | If comp(a, b) and comp(b, c) are true, then comp(a, c) must be true. |
If a < b and b < c, then a < c must hold. |
| Irreflexivity | comp(a, a) must always return false. |
An element is never less than itself. |
| Return Type | The comparison function should return a boolean value. | bool comp(const T& a, const T& b); |
| Consistency | The function should provide consistent results for the same inputs. | Results should not change when called multiple times with the same values. |
| No Modification | The comparison function should not modify its arguments. | It should take const references to avoid modification. |
| Strict Weak Order | The function must impose a strict weak ordering on the elements. | It should behave like a < operator or similar comparison. |
| No Equality Comparison | Equal elements should not return true for either direction. |
If a == b, both comp(a, b) and comp(b, a) should be false. |
