2017-03-03 18 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; 
}