【发布时间】:2019-05-03 16:37:32
【问题描述】:
我为 C++ 凸包算法编写了一个实现,这应该是微不足道的。我下面的代码遵循the paperwork 的公式/方法。我使用名为“Jarvis March”的方法。
它在 20000 点上工作得很好,而在性能方面却少得多,但如果我随机化输入点数组的顺序(使用 std::shuffle),我可以看到有时它会显示错误
对相同点的输入向量进行混洗后:
(绿线是针对给定黑点计算的凸包)
您可能认为该错误与“最后一个”凸包线有关。但它有些不同,在这里可以观察到:
代码:
using namespace std;
vector<Point> m_in;
inline double cross(const Point &a, const Point &b)
{
return (a.x * b.y) - (b.x * a.y);
}
// conterclockwise test
inline bool CCW(const Point &p, const Point &i, const Point &q)
{
// auto a = p.x,
// b = p.y,
// c = i.x,
// d = i.y,
// e = q.x,
// f = q.y;
// the same:
// return ((f - b) * (c - a)) > ((d - b) * (e - a));
// the same:
// Point va { c - a, d - b }; // i - p
// Point vb { e - a, f - b }; // q - p
// return cross(va, vb) > 0;
// the same, compact:
return cross(i - p, q - p) > 0;
}
void Reset(vector<Point> &in)
{
m_in = move(in);
}
vector<Line> GetLine() const
{
vector<Line> res;
Point l = m_in.front();
for(auto &i : m_in)
{
if(l.x < i.x)
{
l = i;
}
}
Point p = l;
for(auto &pi : m_in)
{
Point q = pi;
for(auto &i : m_in)
{
if(CCW(p, i, q))
{
q = i;
}
}
res.push_back(Line { p, q });
p = q;
}
return res;
}
根据图片:
类型,要明确:
struct Point
{
double x, y;
friend Point operator+(const Point& a, const Point& b);
friend Point operator-(const Point& a, const Point& b);
friend bool operator!=(const Point& a, const Point& b);
};
struct Line
{
Point a;
Point b;
};
最后,我没有看到:这段代码的具体错误在哪里?
【问题讨论】:
标签: c++ algorithm convex-hull