Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
247 views
in Technique[技术] by (71.8m points)

c++ - invalid operator < while sorting std::list

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.

enter image description here

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...