Adrian
Adrian

Reputation: 169

Comparison function in c++ error: invalid comparator

I made a simple comaprison function that looks like this:

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

My main function looks like this:

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

The function should arrange an array so that all even numbers are in one part of the array and all odd numbers are in another part of that array.

When I try to run the code, it gives me the error "invalid comparator". Any idea what could be wrong?

Upvotes: 0

Views: 871

Answers (2)

HolyBlackCat
HolyBlackCat

Reputation: 96286

The other answer explains the problem and provides a solution assuming the halves of the resulting array have to be sorted.

If they aren't, you can use a more simple comparator: return a % 2 < b % 2. Then you should also use std::partition instead of std::sort (since it's potentially faster), or std::stable_partition if you want to maintain the original order.

Upvotes: 0

Lukas-T
Lukas-T

Reputation: 11340

I'm assuming that you used this comparator in std::sort. Then it must satisfy the requirement Compare:

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

Ok, your comparator will always return false for equal values.

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

That one fails:

  • function(1, 2) == true, so 1 should come before 2, but ...
  • function(2, 1) == true, so 2 should come before 1, whoops.

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

That one fails to: function(2, 1)==true, function(1, 3)==true, but function(2, 3)==false.


This code should achieve what you want:

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

Sorting [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ] will result in [ 2, 4, 6, 8, 1, 3, 5, 7, 9, ]

Upvotes: 1

Related Questions