In C , std::sort requires a comparison function that adheres to the strict weak ordering rule. This rule ensures that the comparison function returns true if and only if the left operand is less than the right operand.
Consider the provided code:
#includestruct A { A() : a() {} bool operator<(const A& other) const { return a <= other.a; } int a; }; int main() { A coll[8]; std::sort(&coll[0], &coll[8]); // Crash!!! } The custom comparison function returns a <= other.a for equality cases. This violates the strict weak ordering rule, as it states that two elements are considered equal if and only if a == other.a.
By changing the comparison to a < other.a, the rule is satisfied because it returns true only when a is strictly less than other.a. Using a strict ordering prevents the algorithm from entering an infinite loop when encountering equal elements.
In conclusion, std::sort crashes with a non-operator< comparison function because the function violates the strict weak ordering rule, potentially leading to infinite loops. Therefore, it's crucial to ensure your comparison function adheres to this rule to avoid unexpected behavior.
The above is the detailed content of Why Does `std::sort` Crash When Using a Non-Strict Weak Ordering Comparison Function?. For more information, please follow other related articles on the PHP Chinese website!