Mikhail Nono
Mikhail Nono

Reputation: 93

How to sort the segments c++

I have the vector of Edges. I need to sort those edges by y-coordinate of the point of crossing vertical line x==(a+b)/2 and those edges. The problem is the that a and b are not constant and they have to change from one array of edgges to another one. How can I sent the a and b parameters to the comparator?

struct vertex
{

   double x,y;

    bool operator==(const vertex &o)const {
        return x == o.x && y == o.y;
    }

    bool operator<(const vertex &o) const{
        return x < o.x || (x == o.x && y < o.y);
    }

};
typedef vector<vertex> vertList;
typedef vector <pair<vertex,vertex>> Edge;

Upvotes: 0

Views: 751

Answers (1)

kraskevich
kraskevich

Reputation: 18556

You can define a comparator class that takes a and b as constructor arguments:

struct EdgeComparator {
    int a;
    int b;

    EdgeComparator(int a, int b): a(a), b(b) {}

    bool operator<(const Edge& lhs, const Edge& rhs) const {
        // You can compare lhs and rhs using a and b here
    }
};

and later pass its instance to the sort function:

std::sort(v.begin(), v.end(), EdgeComparator(some_value_of_a, some_value_of_b));

Upvotes: 2

Related Questions