我正在用C 撰寫一個帶有機器人的小型模擬,我需要檢查機器人是否發生了碰撞。我在我的模擬類中實作了這個功能:
bool World::isRobotColliding(機器人 *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))。
}
在這里,我的IDE建議我用std::any_of()方法取代for回圈。然而,我無法正確使用它。這就是我所嘗試的:
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()) 。
});
我如何在我的背景關系中使用std::any_of()呢?
謝謝你
uj5u.com熱心網友回復:
謝謝大家的建議,
問題是通過參考傳遞的指標。
return std::any_of(robot. begin(), robots.end(), [r, this](const 機器人 *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;
});
這個代碼段做的正是我所期望的。
我需要在背景關系中傳遞第一個機器人r以及this。我可以在我的機器人中宣告一個距離函式,并省去this。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/315469.html
標籤:
