std :: set 2D点的自定义比较器 [英] std::set custom comparator for 2D points
问题描述
我需要一个非重复2D点的列表,因此我使用具有自定义比较功能的std::set
.我使用的函数在插入点后出现问题,因为有时std::find
找不到已插入的点.
I need a list of non-duplicated 2D points, so I use a std::set
with a custom comparison function. The function I use has problems after inserting points because sometimes the std::find
does not find the already inserted points.
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点有更好的比较功能?
Would I need to preorder the 2d points before inserting into the std::set
or there is a better comparison function for 2d points?
在插入所有点以获得最终点索引之后,我需要使用std::find
.
I need to use std::find
after inserting all points to obtain the final point indexes.
我在Microsoft Visual Studio 2010上使用本机C ++.
I'm using native C++ on Microsoft Visual Studio 2010.
推荐答案
您的比较功能错误.取出+公差.在尝试确定浮点值之间的绝对顺序时,这没有用.例如,它不强制等效性的可传递性.也就是说,如果A == B
(即f(A, B)
和f(B, A)
均为假)和B == C
,则当您在其中进行公差调整时,A == C
并不一定是这种情况.
Your comparison function is wrong. Take out the +-tolerance. That's not useful when trying to determine an absolute order among floating point values. It doesn't enforce transitivity of equivalence, for example. That is, if A == B
(i.e. f(A, B)
and f(B, A)
are both false) and B == C
, then it is not necessarily the case that A == C
when you have that tolerance adjustment in there.
只需执行以下操作:
if (pointA._x < pointB._x) return true;
if (pointA._x > pointB._x) return false;
if (pointA._y < pointB._y) return true;
return false;
这篇关于std :: set 2D点的自定义比较器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!