std::为2D点设置自定义比较器

std::set custom comparator for 2D points

本文关键字:自定义 比较器 设置 2D std      更新时间:2023-10-16

我需要一个不重复的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上使用本机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;

首先,除非你有理由不这样做,否则最好只为你的类定义operator<,这意味着在使用std::set等时可以减少键入,也意味着你可以使用中缀<。其次,正如Benjamin所指出的,不应该有tolerance。第三,你可以简化比较的逻辑。

你应该有这样的东西:

bool operator<(const MyPoint2D& lhs, const MyPoint2D& rhs)
{
    return lhs._x < rhs._x || (lhs._x == rhs._x && lhs._y < rhs._y);
}

然后您可以使用std::set<MyPoint2D>