Comparison function in c++ error: invalid comparator

Comparison function in c++ error: invalid comparator

我做了一个简单的比较函数,看起来像这样:

bool function(int a, int b){
    if (a % 2 == 0) {
        return (a > b);
    }
    if (a % 2 == 1) {
        return (a < b);
    }
    return false;
}

我的主要功能如下所示:

int main() {
    vector<int> vector = {8, 4, 4, 8, 4, 1, 4, 4, 6, 10, 12 };

    sort(vector.begin(), vector.end(), function);

    cout << endl;
    for (int i : vector) {
        cout << i << " ";
    }


    return 0;
}

该函数应安排一个数组,使所有偶数都在数组的一部分中,并且 所有奇数都在该数组的另一部分。

当我尝试 运行 代码时,它给我错误“无效比较器”。知道哪里出了问题吗?

我假设您在 std::sort 中使用了这个比较器。那么它必须满足要求 Compare:

For all a, comp(a,a)==false

好的,你的比较器总是 return false 相等的值。

If comp(a,b)==true then comp(b,a)==false

那个失败了:

  • function(1, 2) == true,所以 1 应该在 2 之前,但是...
  • function(2, 1) == true,所以 2 应该在 1 之前,哎呀。

if comp(a,b)==true and comp(b,c)==true then comp(a,c)==true

那个失败了:function(2, 1)==truefunction(1, 3)==true,但是 function(2, 3)==false


这段代码应该可以实现你想要的:

bool function(int a, int b){
    if(a % 2 == b % 2) {
        // If both are even or both are odd simply compare the numbers
        return a < b;
    } 
    else {
        // if one is even and the other is odd then
        // a should come before b if a is even
        return a % 2 == 0; 
    }
}

排序 [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ] 将得到 [ 2, 4, 6, 8, 1, 3, 5, 7, 9, ]

另一个答案解释了问题并提供了一个解决方案,假设必须对结果数组的一半进行排序。

如果不是,您可以使用更简单的比较器:return a % 2 < b % 2。然后你也应该使用 std::partition 而不是 std::sort (因为它可能更快),或者如果你想保持原来的顺序 std::stable_partition