The Visual Studio sort function appears "Invalid operator<" cause analysis

Source: Internet
Author: User

There is a "invalid operator<" problem when using sort in the afternoon, for specific information see

And then I'm quite puzzled, because this is usually the case with the default comparison operator, which is:

Template <class randomaccessiterator>  void sort (randomaccessiterator first, Randomaccessiterator last);

But you clearly use the second function of the overloaded function, namely:

Template <class compare>  void sort (randomaccessiterator first, Randomaccessiterator last, Compare comp);

Later, by querying the online data, I found that the cause of the problem is that VC for the comparison function will be strict weak ordering confirmation. (This has just been a bit of a surprise)

Direct excerpt from the official website explains:

Results:

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

Compare your own code and find that the problem is pred (x, x) = True, then the solution is generated (<= replaced by <).

Finally, I enclose the comparison function in my initial code.

// compare weights for two edges BOOL Const Const Edge & E2) {    return e1.weight <= e2.weight;}

The Visual Studio sort function appears "Invalid operator<" cause analysis

Related Article

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.