Tom*_*mas 0 c++ for-loop if-statement boolean return
我正在研究一个函数,如果任何一个点位置在定义的矩形边界之外,它应该返回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;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
由于某种原因,true即使其中一个点超出指定的边界,它也会返回.我不认为应该是这种情况.我应该重写这个功能并单独检查每个点还是有另一种方法?
谁能指出我在这里做错了什么?谢谢.
您根据第一点的检查返回,而不继续检查任何其他点.如果在区域外找到一个点,则应返回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;
}
Run Code Online (Sandbox Code Playgroud)
......或者,更具声明性......
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;
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
766 次 |
| 最近记录: |