gpt4 book ai didi

c++ - 如何对段进行排序 C++

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:14:13 25 4
gpt4 key购买 nike

我有边 vector 。我需要通过垂直线 x==(a+b)/2 和那些边的交叉点的 y 坐标对这些边进行排序。问题是 a 和 b 不是常量,它们必须从一个边缘数组更改为另一个边缘数组。如何将 a 和 b 参数发送到比较器?

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;

最佳答案

您可以定义一个比较器类,将 ab 作为构造函数参数:

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

然后将其实例传递给排序函数:

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

关于c++ - 如何对段进行排序 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43579246/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com