您的位置:首页 > 大数据 > 人工智能

Assertion Failure When Sorting STL Vector using Custom Predicate

2015-11-17 10:46 513 查看
程序在运行过程中出现断言错误"invalid operator <",这是因为在vs2005之后的版本出现了strict weak ordering,要求operator <在处理==的情况需要返回false

https://support.microsoft.com/en-us/kb/949171

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; //Should return false if both the vaules are same
}


Second Option:

bool CustPredicate (int elem1, int elem2 )
{
return elem1 > elem2;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: