Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...