在VS2008/2010中SORT,stable_sort的比较函数是strict weak ordering。当比较的时候出现元素相等的情况是编译器默认必须返回false,而如果在自定义比较函数时,将相等返回true。将会出现invalid operator<的异常。

注意:这种异常在DEVCPP中时不会出现的。

如:

1 bool cmp(datatype x,datatype y)
2 {if(x>y)
3  return true;
4 if(x==y)
5 return true;//x==y,返回true,将出现invalid operator<异常
6 return false;
7 }

 

所以当比较出现相等的时候必须返回false;

 

即:

bool cmp(datatype x,datatype y)
{
if(x>y)
return true;
if(x<y)
return false;

return false;//当x==y时,返回false;
}

Assertion Failure When Sorting STL Vector using Custom Predicate

Article ID: 949171 - View products that this article applies to.
Source: Microsoft Support
 

关于VS2008/2010中SORT,stable_sort的比较函数中strict weak orderingRAPID PUBLISHING

RAPID PUBLISHING ARTICLES PROVIDE INFORMATION DIRECTLY FROM WITHIN THE MICROSOFT SUPPORT ORGANIZATION. THE INFORMATION CONTAINED HEREIN IS CREATED IN RESPONSE TO EMERGING OR UNIQUE TOPICS, OR IS INTENDED SUPPLEMENT OTHER KNOWLEDGE BASE INFORMATION.
 

关于VS2008/2010中SORT,stable_sort的比较函数中strict weak orderingAction

1 bool CustPredicate (int elem1, int elem2 )
2 {
3     if(elem1 > elem2)
4         return true;
5 
6     if (elem1 < elem2)
7         return false;
8     return true;
9 }

 









 

关于VS2008/2010中SORT,stable_sort的比较函数中strict weak orderingResult

It works fine in Visual C++ 2002 and Visual C++ 2003.
It throws and assertion failed error, "Expression: invalid operator < " in Visual C++  2005 and Visual C++ /2008.
 

关于VS2008/2010中SORT,stable_sort的比较函数中strict weak orderingCause



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).







关于VS2008/2010中SORT,stable_sort的比较函数中strict weak orderingResolution

 1 bool CustPredicate (int elem1, int elem2 )
 2 {
 3     if(elem1 > elem2)
 4         return true;
 5 
 6     if (elem1 < elem2)
 7         return false;
 8 
 9     return false; //Should return false if both the vaules are same
10 }

 


1 bool CustPredicate (int elem1, int elem2 )
2 {
3     return elem1 > elem2;
4 }

相关文章:

  • 2021-11-06
  • 2023-03-19
  • 2022-12-23
  • 2022-02-18
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-01-06
  • 2022-12-23
  • 2021-08-06
  • 2022-12-23
相关资源
相似解决方案