简体   繁体   English

检查点是否在向量内

[英]Check if point is inside vector

I want to check if a given point with x and y value is inside a vector of points: 我想检查xy值的给定点是否在点向量内:

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;
}

Are there other approaches without the for loop? 还有其他没有for循环的方法吗?

You can use std::find or std::find_if with suitable functor to avoid writing your own loop. 您可以将std :: find或std :: find_if与合适的函子一起使用,以避免编写自己的循环。 But you don't gain in terms of complexity: it is still O(n). 但是您不会从复杂性方面获益:它仍然是O(n)。 For example, 例如,

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);

or, without the equality operator, 或者,如果没有相等运算符,

auto it = std::find_if(points.begin(), 
                       points.end(), [&somePoint](const Point2Di& p)
                                     {return somePoint.x == p.x && somePoint.y == p.y;});

Assumming you have an operator== defined for your Point2i structure, you can use std::find() , like this: 假设您为Point2i结构定义了一个operator== ,则可以使用std :: find() ,如下所示:

std::vector<Point2i>::const_iterator findIt = std::find(
    points.begin(),
    points.end(),
    Point2i(x, y));

I also assume you have a Point2i constructor that takes the two coordinates. 我还假设您有一个使用两个坐标的Point2i构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM