我想检查xy值的给定点是否在点 vector 内:

bool inside_vector(int x, int y, vector<Point2i>& points)
{
  for(vector<Point2i>::const_iterator it = points.begin();
    it != points.end();
    ++it)
  {
    if(it->x == y && it->y == y)
    {
      return true;
    }
  }
  return false;
}

还有没有for循环的其他方法吗?

最佳答案

您可以将std::find or std::find_if与合适的函子一起使用,以避免编写自己的循环。但是您不会从复杂性方面获益:它仍然是O(n)。例如,

bool operator==(const Point2i& lhs, const Point2i& rhs)
{
  return lhs.x == rhs.x && lhs.y == rhs.y;
}

Point2Di somePoint = Point2Di(x,y); // point to find
auto it = std::find(points.begin(), points.end(), somePoint);

或者,如果没有相等运算符,
auto it = std::find_if(points.begin(),
                       points.end(), [&somePoint](const Point2Di& p)
                                     {return somePoint.x == p.x && somePoint.y == p.y;});

10-07 20:06
查看更多