When using the STL sort template function, I encountered a runtime error and thought it was very strange. I searched for it. In Versions later than vc05, I checked whether the comparison function was strict weak ordering, by the way, we learned about strict weak ordering. The VC runtime check mechanism is also intriguing. This isArticleLink:
Http://hi.baidu.com/haochaoqing/item/00b40cf2b8c4efc0a835a255
Http://support.microsoft.com/kb/949171
Paste the content of article 2 as follows:
Action
Sort any STL collection using stable_sort () or sort () with duplicate items using the following custom Predicate
Bool custpredicate (INT elem1, int elem2)
{
If (elem1> elem2)
Return true;
If (elem1 <elem2)
Return false;
Return true;
}
Result
It works fine in visbual C ++ 2002 and Visual C ++ 2003.
It throws and assertion failed error, "expression: Invalid operator <" in Visual C ++ 2005 and Visual C ++/2008.
Cause
The STL algorithms for stable_sort () and sort () require the binary predicate to be strict weak ordering.
For example:
· Strict: PRED (x, x) is always false.
· Weak: If! PRED (x, y )&&! PRED (Y, x), x = y.
· Ordering: If PRED (x, y) & PRED (Y, Z), then PRED (x, z ).
Resolution
Below either of the options will resolve the issue
First option :-
Bool custpredicate (INT elem1, int elem2)
{
If (elem1> elem2)
Return true;
If (elem1 <elem2)
Return false;
Return false; // shocould return false if both the vaules are same
}
Second option :-
Bool custpredicate (INT elem1, int elem2)
{
Return elem1> elem2;
}