invalid operator < while sorting std::list
Your comparator returns true
when both relevant fields are equal. This is invalid, so it may well be what the sort
implementation has detected via assert.
You're supposed to pass a "less than" predicate to sort
: formally a "strict weak order". Anything else is undefined behavior. It seems in this case you got lucky, and the implementation detects that it has got into an impossible situation due to inconsistent comparisons.
Abdul Samad
Updated on June 10, 2022Comments
-
Abdul Samad almost 2 years
I have a std::list graph edges and i want to sort the edges based on their destination outdegree and then their indegree. But i am getting getting exception of invalid operator < during my comparison function below is my code. My list contains the pointers to the edges and edges have destination nodes as their member.
bool compareEdges(const Edge *e1,const Edge *e2){ if(e1->destination->outdegree < e2->destination->outdegree){ return true; } else if(e1->destination->outdegree > e2->destination->outdegree){ return false; } else if(e1->destination->indegree > e2->destination->indegree){ return false; } return true;
}
And here is the call to the sort function.
currentNode->edgeList.sort(compareEdges);
Please help me in removing this exception.
Thanks
-
Abdul Samad over 12 yearsWhat does sort have to do if two things are equal in my opinion it just needs a return true or false value. Can you please elaborate a little bit more how it should be if want to sort the edges first on the basics of outdegree and if they are same then on the basics of indegree.
-
Steve Jessop over 12 yearsIt must return
false
when they're equal, I'm afraid your opinion doesn't enter into it ;-) The comparator should behave like "less than", andx < x
is false. If you want to know the precise requirements, look up the definition of a "strict weak order". -
Abdul Samad over 12 yearsSo did u mean that i should not return any thing when two values are equal?
-
Michael Krelin - hacker over 12 years@AbdulSamad, it's just that you end up with
a < b
andb < a
both true. -
Steve Jessop over 12 years@Abdul: no, I don't mean that you shouldn't return anything. I mean what I said, return
false
. -
visitor over 12 years
else if(e1->destination->indegree >= e2->destination->indegree)
- This greater-or-equal modification should turn it into a valid comparator. You really can't sort something ifa
should go both before and afterb
(a<b && b<a == true
)