2017-03-03 17 views
0

我正在处理一个函数,如果任何点位置都在定义的矩形边界之外,则该函数应该返回false。如果任何条件为假,如何从for循环返回false

我当前的C++代码如下:

bool trackingPointsVisible(){ 
     //I've got 4 points here 
     if(!points.empty()){ 
       // loop through each of the points 
      for(int i=0; i<points.size(); i++){ 
        //check if points' x and y positions are out of the boundaries 
       if(points[i].x < -60 || points[i].x > 300 || 
       points[i].y < -60 || points[i].y > 300){ 
        // if any of them are out return false 
        return false; 
       }else{ 
        //if they're within the boundaries, return true 
        return true; 
       } 

      } 
     } 
    } 

出于某种原因,它返回true即使其中一个点,如果超出规定的边界。我不认为这应该是这样。我应该重写这个函数并单独检查每个点还是有另一种方法?

任何人都可以请指出我在这里做错了什么?谢谢。

+1

当'points'为空时,请注意您的未定义行为,因为在该路径上不会返回。在任何情况下,如果'size'为0('i'永远不会小于'0),那么'if'是多余的,因为'for'循环不会运行迭代。 –

+0

你确定你的条件满足吗?因为你的代码看起来对我来说是正确的,所以它看起来像是一个数据问题 – EdChum

+0

由于你需要其他方法,['std :: find_if'](http://en.cppreference.com/w/cpp/algorithm/find)可以很容易地用来解决这个问题。 –

回答

5

您根据第一个点的检查返回,而不继续检查其他任何其他点。如果在区域外找到一个点,则应该返回false,否则继续检查其余点,只在循环外返回true。

不管它的价值,可以简化代码位:

bool trackingPointsVisible() 
{ 
    for (const auto& point : points) 
     //check if points' x and y positions are out of the boundaries 
     if (point.x < -60 || point.x > 300 || 
      point.y < -60 || point.y > 300) 
      return false; 
    return true; 
} 

...或者,更声明...

bool trackingPointsVisible() 
{ 
    // check none of the points are out of bounds... 
    return std::none_of(std::begin(points), std::end(points), 
         [](const Point& point) { 
          return point.x < -60 || point.x > 300 || 
            point.y < -60 || point.y > 300; 
         }); 
} 
+1

我看到我现在犯了错误,也感谢代码的简化版! – Tomas

1

所有的功能首先是未定义的行为,因为当容器points为空时它不返回任何内容。

其次,只有在所有点都被检查的情况下,您才必须返回true。这是真正的return语句必须在循环之外。

该功能可以通过以下方式定义。

bool trackingPointsVisible() 
{ 
     //I've got 4 points here 
     size_t i = 0; 

     while (i < points.size() and not 
       (points[i].x < -60 || points[i].x > 300 || 
        points[i].y < -60 || points[i].y > 300)) i++; 

     return i == points.size(); 
} 

声明

size_t i = 0; 

可以取代

decltype(points)::size_type i = 0; 

例如

bool trackingPointsVisible() 
{ 
     //I've got 4 points here 
     decltype(points)::size_type i = 0; 

     while (i < points.size() and not 
       (points[i].x < -60 || points[i].x > 300 || 
        points[i].y < -60 || points[i].y > 300)) i++; 

     return i == points.size(); 
} 
1

您只能在函数的最后返回true:

bool trackingPointsVisible(){ 
    //I've got 4 points here 
    if(!points.empty()){ 
     // loop through each of the points 
     for(int i=0; i<points.size(); i++) { 
      //check if points' x and y positions are out of the boundaries 
      if(points[i].x < -60 || points[i].x > 300 || 
      points[i].y < -60 || points[i].y > 300) { 
       // if any of them are out return false 
       return false; 
      } 
     } 
    } 

    return true; 
}