I'm coding a small simulation in c with robots and I need to check if the robot are colliding. I implemented this function in my simulation's class:
bool World::isRobotColliding(Robot *r) {
for (Robot *other_robot: robots) {
double d = distance(r->getX(), r->getY(), other_robot->getX(), other_robot->getY());
if ((r->getRadius() other_robot->getRadius()) >= d) return true;
}
return false;
}
double World::distance(const double &x_1, const double &y_1, const double &x_2, const double &y_2) const {
return sqrt((x_1 - x_2) * (x_1 - x_2) (y_1 - y_2) * (y_1 - y_2));
}
Here my IDE suggested me to replace the for loop with the std::any_of() method. However, I was unable to use it properly. This is what I tried:
return std::any_of(robots.begin(), robots.end(), [r, this](const Robot *&other_robot) {
return
(r->getRadius() other_robot->getRadius())
>=
distance(r->getX(), r->getY(), other_robot->getX(), other_robot->getY());
});
How can I use std::any_of() in my context?
Thank you
CodePudding user response:
Thank you everyone for your advise,
The issue was the pointer passed by reference.
return std::any_of(robots.begin(), robots.end(), [r, this](const Robot *other_robot) {
double d = distance(r->getX(), r->getY(), other_robot->getX(), other_robot->getY());
if(d == 0) return false;
return
(r->getRadius() other_robot->getRadius())
>=
d;
});
This snippet do exactly what I was expecting.
I needed to pass the first robot r
in the context as well as this
. I could have declared a distance function in my robot and ommiting the this
.