作者:安徒生童话13 | 来源:互联网 | 2022-11-28 17:44
我有一个项目,我有一个包含机器人对象的游戏文件.游戏文件使用地图保存机器人对象.地图包含机器人的名称作为键,值是机器人对象.
机器人在2D空间中,并且它们具有x,y以找到它们的当前位置.
我必须实现的功能之一是通过查找机器人与原点(0,0)的距离,将机器人从最小到最大排序.
这是我的地图:
std::map robot_map;
我使用名称和两个变量初始化机器人以了解位置,并使用第三个变量来查找所采取的步骤总数:
robot::robot(const string &n) : robot_name(n) { x = 0, y = 0, t = 0; }
为了检查机器人与原点的距离我使用:
std::string game::furthest() const
{
int furthest = 0;
std::string max_name;
typedef std::map::const_iterator iter;
for (iter p = robot_map.cbegin(); p != robot_map.cend(); ++p) {
if (distance(p->second) > furthest) {
furthest = distance(p->second);
max_name = p->first;
}
}
return max_name;
}
这是距离函数:
int distance(const robot &r) {
int distance;
int y = r.north();
int x = r.east();
distance = abs(x - 0) + abs(y - 0);
return distance;
}
在我的上一个函数中,我想在向量中对它们进行排序,这就是我目前所拥有的:
std::vector game::robots_by_travelled() const
{
std::vector robots;
int furthest = 0;
typedef std::map::const_iterator iter;
for (iter p = robot_map.cbegin(); p != robot_map.cend(); ++p) {
robots.push_back(p->second);
}
return robots;
;
}
有没有办法按照距离原点(0,0)的距离对矢量进行排序?
1> molbdnilo..:
是的,有std::sort
任何适当的关系:
std::sort(robots.begin(),
robots.end(),
[](const robot& lhs, const robot& rhs)
{ return distance(lhs)
或者,如果你想要一个可重用的谓词:
bool closer(const robot& r1, const robot& r2)
{
return distance(r1)
你也可以重载<
操作员,然后说
std::sort(robots.begin(), robots.end());
但是当你的对象有意义地被称为彼此"小于"并且你想<
在其他情况下也是如此时更有意义.