[英]how can I find the minimum distance between two point by using inheritance?
[英]How to find minimum distance using lambda
我有两个类Entity
和Ship
。 Ship
继承自Entity
。 它们具有x
和y
作为属性,代表二维平面上的 position。
squared_distance
function 返回船舶和实体之间的距离。
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);
}
我需要找到离船最近的实体。 我有一个名为entities
的Entity
数组。 一种方法是:让ship
是Ship
的 object 。
index
将给出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;
}
}
如何在算法库中使用带有std::min_element
的 lambda 找到最近的实体?
int squared_distance(const Entity& e, const Ship& s)
{
return pow((e.x - s.x), 2) + pow((e.y - s.y), 2);
}
std::min_element(std::begin(entities), std::end(entities), [&ship](const Entity& a, const Entity& b) { return squared_distance(a, ship) < squared_distance(b, ship); });
请注意,您需要更新squared_distance
声明中的参数。
您可以像这样将其转换为std::min_element
:
auto closer = [&ship](const auto &e1, const auto &e2) {
return squared_distance(e1, ship)
< squared_distance(e2, ship);
};
auto it = std::min_element(std::begin(entities), std::end(entities), closer);
请注意,此算法(与大多数算法一样)将返回一个iterator
到最近的船。 您可以通过取消引用此迭代器来获得最近的船:
auto closest_ship = *it;
您还可以获得这艘船的索引(就像您的版本一样):
int i = std::distance(std::begin(entities), it);
正如@SM 在他们的回答中指出的那样,您的squared_distance
function 应该通过const&
获取其参数,因为您不需要复制这些对象来比较它们。
就像是
#include <iterator>
#include <algorithm>
//...
auto it = std::min_element( std::begin( entities ), std::end( entities ),
[&ship]( const auto &first, const auto &second )
{
return squared_distance( first, ship ) < squared_distance( second, ship );
} );
您可以单独定义 lambda,例如
auto less_distance = [&ship]( const auto &first, const auto &second )
{
return squared_distance( first, ship ) < squared_distance( second, ship );
};
然后算法的调用看起来像
auto it = std::min_element( std::begin( entities ), std::end( entities ),
less_distance );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.