我正在处理一个函数,如果任何点位置都在定义的矩形边界之外,则该函数应该返回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)可以很容易地用来解决这个问题。 –