Home > other >  C - issues with writing sorting function
C - issues with writing sorting function

Time:11-11

I have a problem with sorting function.

I have following struct:

struct Object {
    int value, height;
    Object(int v, int h) {
        this->value = v;
        this->height = h;
    }
};

I am storing vector of this objects: std::vector<Object> v

And I'd like to sort it such that if the height is greater than some i then it should go at the end, and if it is less or equal sort by value.

I've tried this before:

// some value
int i = 4;

std::sort(v.begin(), v.end(), [ & ](Object a, Object b) {
    if (b.height > i) {
        return false;
    }
    if (a.height > i) {
        return false;
    }

    return a.value > b.value;
});

But it does not seem to work..

When I have these elements:

std::vector<Object> v = {{3, 10}, {5, 2}, {3, 2}, {2, 10}, {2, 1000000000}}; and i = 2

When I print values of v, after sorting I see that they appear in the exact same order

And I'd like them in the following order: {{5, 2}, {3, 2}, {3, 10}, {2, 10}, {2, 1000000000}}

CodePudding user response:

It seems you want something like:

std::sort(v.begin(), v.end(), [ & ](const Object& lhs, const Object& rhs) {
    return std::make_pair(lhs.height > i, lhs.value) < std::make_pair(rhs.height > i, rhs.value);
});

CodePudding user response:

I think this is also a solution for your problem:

std::sort(v.begin(), v.end(), [ & ](Object a, Object b) {
    if (b.height > i) {
        // Here is change
        return true;
    }
    if (a.height > i) {
        return false;
    }

    return a.value > b.value;
});

Just in the first if instead of returning false return true

  • Related