How does below comparator function works in c++?

前端 未结 2 893
情深已故
情深已故 2021-01-28 17:13
bool comp(int a,int b){

    if ((a > 0 && b > 0) || (a < 0 && b < 0))
        return false;

    if ((a > 0) && (b < 0))
              


        
2条回答
  •  误落风尘
    2021-01-28 18:05

    Your assertions are incorrect on two counts:

    1. std::sort is not guaranteed to preserve the order of elements that don't need sorting, if you get my meaning.

    2. The behaviour of your comp function is undefined as it doesn't have an explicit return value on all control paths.

    One remedy is to use std::stable_sort which will preserve the order of elements as best it can. The comparator function can be adjusted such that it's true if the first argument is negative and the second is positive (let's define 0 to be positive):

    bool comp(int a, int b){
        return a < 0 && b >= 0;
    }
    

    Another remedy is to use std::stable_partition.

提交回复
热议问题