我正在處理一個函數,如果任何點位置都在定義的矩形邊界之外,則該函數應該返回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
即使其中一個點,如果超出規定的邊界。我不認爲這應該是這樣。我應該重寫這個函數並單獨檢查每個點還是有另一種方法?
任何人都可以請指出我在這裏做錯了什麼?謝謝。
當'points'爲空時,請注意您的未定義行爲,因爲在該路徑上不會返回。在任何情況下,如果'size'爲0('i'永遠不會小於'0),那麼'if'是多餘的,因爲'for'循環不會運行迭代。 –
你確定你的條件滿足嗎?因爲你的代碼看起來對我來說是正確的,所以它看起來像是一個數據問題 – EdChum
由於你需要其他方法,['std :: find_if'](http://en.cppreference.com/w/cpp/algorithm/find)可以很容易地用來解決這個問題。 –