我想检查具有 x
和 y
值的给定点是否在点 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/