Search code examples
c++sortingstl-algorithm

<algorithm> sort custom condition


Okay, so I've tried to use sort to vector of items so the size of two adjecant items is <= 2d. So here's my attempt:

struct item{
    long number;
    long size;
};

// d is global variable.
bool check(const item& x, const item& y)
{
    return ((x.size + y.size) <= (2 * d));
}

// Items is a vector of item.
sort(items.begin(), items.end(), check); 

What am I doing wrong or it's even impossible to sort using condition like that ?


Solution

  • it's even impossible to sort using condition like that ?

    No. The comparer in sort must satisfy the criteria of a strict weak ordering which yours clearly doesn’t (for instance it’s not irreflexive).