我想检查具有x和y值的给定点是否在点向量内:
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;
}
Run Code Online (Sandbox Code Playgroud)
没有for循环还有其他方法吗?
您可以将std :: find或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);
Run Code Online (Sandbox Code Playgroud)
或者,没有相等运算符,
auto it = std::find_if(points.begin(),
points.end(), [&somePoint](const Point2Di& p)
{return somePoint.x == p.x && somePoint.y == p.y;});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1030 次 |
| 最近记录: |