gpt4 book ai didi

c++ - std::set 自定义比较器用于 2D 点

转载 作者:搜寻专家 更新时间:2023-10-30 23:55:02 25 4
gpt4 key购买 nike

我需要一个不重复的 2D 点列表,所以我使用了一个带有自定义比较函数的 std::set。我使用的函数在插入点后出现问题,因为有时 std::find 找不到已经插入的点。

const double tolerance = 0.1;
struct MyPoint2D
{
MyPoint2D(double x, double y) : _x(x), _y(y) {}
double _x, _y;
};
auto compMyPoint2D = [&](const MyPoint2D& pointA, const MyPoint2D& pointB) -> bool
{
if (pointA._x < pointB._x - tolerance) return true;
if (pointA._x > pointB._x + tolerance) return false;
if (pointA._y < pointB._y - tolerance) return true;
return false;
};
std::set<MyPoint2D, decltype(compMyPoint2D)> orderedMyPoints(compMyPoint2D);
MyPoint2D pointA(0.66,1.14);
MyPoint2D pointB(0.75, 0.0);
MyPoint2D pointC(0.57,1.19);
orderedMyPoints.insert(pointA);
orderedMyPoints.insert(pointB);
orderedMyPoints.insert(pointC);
if (orderedMyPoints.find(pointC)==orderedMyPoints.end())
{
std::cout << "Not found" << std::endl;
orderedMyPoints.insert(pointC);
if (orderedMyPoints.find(pointC)==orderedMyPoints.end())
std::cout << "Still not found" << std::endl;
}

我是否需要在插入 std::set 之前预先排序 2d 点,或者有更好的 2d 点比较函数?

我需要在插入所有点后使用 std::find 来获取最终的点索引。

我在 Microsoft Visual Studio 2010 上使用 native C++。

最佳答案

你的比较功能是错误的。取出 +-公差。这在尝试确定浮点值之间的绝对顺序时没有用。例如,它不强制等价的传递性。也就是说,如果 A == B(即 f(A, B)f(B, A) 都是假的)并且 B == C,那么 A == C 当你在那里进行容差调整时不一定是这种情况。

只需这样做:

if (pointA._x < pointB._x) return true;
if (pointA._x > pointB._x) return false;
if (pointA._y < pointB._y) return true;
return false;

关于c++ - std::set 自定义比较器用于 2D 点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34047772/

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