c++ - 检查点是否在 vector 内

标签 c++ opencv

我想检查具有 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;});

关于c++ - 检查点是否在 vector 内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16008865/

相关文章:

c++ - 不同来源的QT调用函数

c++ - 在C++中可以做 “call by reference when possible”吗?

c++ - 混合语言 F77/C++ : Avoid destruction of C++ instance

C++:捕获 block 没有捕获?

c++ - 使用 OpenCV 将图像旋转 90 度的最简单方法?

python - 如何仅提取图像的圆形 ROI 部分并通过在 Python OpenCV GUI 的 Tkinter 窗口中单击按钮来显示圆的半径

c++ - 当我使用thread和mutex时,C++发生Memory leak

image - 如何基于二进制掩码裁剪图像

opencv - 计算平行平面的单应性

ios - 如何优化opencv的calcOpticalFlowPyrLK?