2013-04-15 35 views
1

我要檢查是否有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; 
} 

是否有未經for循環其他方法?

回答

5

您可以使用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;}); 
3

Assumming你有你的Point2i結構定義的operator==,您可以使用std::find(),像這樣:

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

我還假設你有一個帶有兩個座標的構造函數Point2i