Casper7526
Casper7526

Reputation: 341

Sorting a vector based on multiple value types

I'm looking to sort a custom struct based on multiple values... I've handled instances where I had to sort by 2 different numbers just fine using < > in a custom sort method... except this time I have to sort by 2 booleans and a number.

struct MyStruct
{
B1 = false;
B2 = true;
N1 = 0;
}

Now... I want it to sort as the following...

Anything that has B1 and B2 true comes first. Anything that has B1 comes next.

Those 2 sections need to also be sorted by N1 (lower = comes first)

So B1 and B2's need to be ordered N1 lowest to highest. Followed by just B1's ordered N1 lowest to highest. Followed by everything else ordered lowest to highest.

Here's my attempt so far...

    if (lhs.boss && lhs.isLOS && lhs.distancetome < rhs.distancetome)
        return true;
    if (lhs.boss && lhs.isLOS && lhs.distancetome > rhs.distancetome)
        return false;
    if (lhs.boss && lhs.distancetome < rhs.distancetome)
        return true;
    if (lhs.boss && lhs.distancetome > rhs.distancetome)
        return false;
    if (lhs.distancetome < rhs.distancetome)
        return true;

    return false;

Upvotes: 0

Views: 54

Answers (1)

Revolver_Ocelot
Revolver_Ocelot

Reputation: 8785

Something like that:

struct complex_comparison
{
    bool operator()(const MyStruct& lhs, const MyStruct& rhs)
    {
        return lhs.B1 && lhs.B2 != rhs.B1 && rhs.B2 ? lhs.B1 && lhs.B2 > rhs.B1 && rhs.B2 :
                                   lhs.B1 != rhs.B1 ? lhs.B1 > rhs.B1 :
                                   lhs.N1 < rhs.N1;
    }
};

Example: http://coliru.stacked-crooked.com/a/b4888ac34d2ca6bb

Upvotes: 1

Related Questions