Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ – issues with writing sorting function

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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);
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading