I am trying to sort a vector of pointers to a class A using std::sort, but am having some difficulties.

Imagine class A beings just a point, containing x and y coordinates. I want to sort the vector by y coordinates from biggest to lowest using some fixed offset value. And on top of this I want to sort it by x coordinatex, from lowest to biggest. I've had something like following in mind but as you can imagine its not working as wanted:

```
bool A::sortByCoordinates(const A *a, const A *b)
{
if ((b->y < a->y - offset) || (b->y > a->y + offset)) {
return false;
} else if (b->x < a->x) {
return true;
}
return false;
}
void A::recalculate(std::vector<A *> &test)
{
std::sort(test.begin(), test.end(), sortByCoordinates);
}
```

In short, if `b->y < a->y - offset`

or `b->y > a->y + offset`

treat it as `b->y == a->y`

and then sort by their x coordinates from lowest to biggest. If the above is not true sort it as `b->y < a->y`

.

How can I achieve this?

**EDIT:**

Imagine a xy plane such as this:

where black dots represent class A with x and y coordinates. I want to split this plane into finitely many sections which are represented by the red lines and are wide as `offset`

. Now I want to treat points in these sections as tho they had the same y coordinate and sort them only by their x coordinate.

# Best How To :

```
(b->y < a->y - offset) || (b->y > a->y + offset)
```

These are two different cases, which should have different results. I suppose that `b`

is "less" then `a`

in first case, and "greater" in the other case, but your code returns false for both cases. See @Jonathan's answer on how to fix this.

But also note a that your approach (considering all y's that differ by less than `offset`

equal) has a major flaw: it will not generate a strict total order. Assume you have `offset=3`

and three points `A(x=0,y=0)`

, `B(x=-2,y=2)`

and `C(x=-4,y=4)`

.

You will have `A`

and `B`

falling within `offset`

by `y`

coordinate so you will compare `A.x`

and `B.x`

and get `A<B`

. Similarly you get `B<C`

, but `A`

and `C`

do not fall within `offset`

distance, so you get `A>C`

, that is `A<B<C<A`

, which should never be. (Tweak the coordinates if I get your ordering wrong). Therefore you first need to reconsider your ordering concept.

If (as you specify in the edit) you want to divide into horizontal stripes, and sort points within a stripe by x, then you should not check whether the `y`

s differ by no more than `offset`

, because two points can have their `y`

s differ by less then `offset`

, but still be located in different stripes. I would suggest to explicitly calculate the stripe number and compare them, something like

```
bool A::sortByCoordinates(const A& a, const A& b)
{
// get stripe numbers, assuming A::y to be positive int
int stripeA = a.y / offset; // be careful if a.y can be negative!
int stripeB = b.y / offset;
if (stripeA != stripeB)
return stripeA < stripeB;
return a.x < b.x;
}
```