我需要一个非重复的 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;
}
在插入之前我需要预先订购 2d 点吗std::set
或者有更好的2d点比较函数?
我需要使用std::find
插入所有点后得到最终的点索引。
我在 Microsoft Visual Studio 2010 上使用本机 C++。
你的比较函数是错误的。去掉+-公差。当尝试确定浮点值之间的绝对顺序时,这没有用。例如,它不强制等价的传递性。也就是说,如果A == B
(i.e. f(A, B)
and 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;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)