I have two classes Entity and Ship. Ship is inherited from Entity. They have x and y as attributes which represents there position on 2D plane.
squared_distance function returns distance between a ship and an entity.
class Entity
{
public:
int id, x, y;
Entity(int id, int x, int y) : id(id), x(x), y(y) {}
};
class Ship : public Entity
{
public:
int orientation, speed, rum;
Ship(int id, int x, int y, int ori, int s, int r):
Entity(id, x, y)
{
orientation = ori;
speed = s;
rum = r;
}
};
int squared_distance(Entity e, Ship s)
{
return pow((e.x - s.x), 2) + pow((e.y - s.y), 2);
}
I need to find the nearest entity to the ship. I have an array of Entity named entities. One way to do that is: Let ship is object of Ship.
index will give the index of nearest entity to the ship.
int min_distance = 10000000;
int index;
for (int i = 0; i < entities.size(); ++i)
{
int curr_distance = squared_distance(entities[i], ship);
if (curr_distance < min_distance)
{
min_distance = curr_distance;
index = i;
}
}
How to find nearest enity using lambda with std::min_element in algorithm library?
Aucun commentaire:
Enregistrer un commentaire