"Invalid operator" occurs when you specify the comparison function of STD: sort in VC.

Source: Internet
Author: User

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;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.