首页 > 解决方案 > C++ 中的比较函数错误:无效的比较器

问题描述

我做了一个简单的comaprison函数,如下所示:

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;
}

该函数应该排列一个数组,以便所有偶数都在数组的一部分中,而所有奇数都在该数组的另一部分中。

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

标签: c++functioncomparison

解决方案


我假设您在std::sort. 那么它必须满足比较的要求:

对于所有一个,comp(a,a)==false

好的,您的比较器将始终返回false相等的值。

如果comp(a,b)==true那时comp(b,a)==false

那一个失败了:

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

如果comp(a,b)==true然后comp(b,c)==true_comp(a,c)==true

那一个失败了:function(2, 1)==true, function(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, ]


推荐阅读