【发布时间】:2018-11-22 15:52:00
【问题描述】:
我有一个项目,其中有一个包含机器人对象的游戏文件。游戏文件使用地图保存机器人对象。该映射包含机器人的名称作为键,值是机器人对象。
机器人在 2D 空间中,它们有 x,y 来找到它们的当前位置。
我必须实现的功能之一是通过查找机器人与原点 (0, 0) 的距离来从最小到最大对机器人进行排序。
这是我的地图:
std::map<std::string, robot> 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<std::string, robot>::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<robot> game::robots_by_travelled() const
{
std::vector<robot> robots;
int furthest = 0;
typedef std::map<std::string, robot>::const_iterator iter;
for (iter p = robot_map.cbegin(); p != robot_map.cend(); ++p) {
robots.push_back(p->second);
}
return robots;
;
}
有没有办法按照向量与原点的距离(0, 0)对向量进行排序?
【问题讨论】:
-
你知道
std::stort,尤其是比较器的过载吗? -
顺便说一句,
distance不是欧几里得。对吗? -
std::sort(begin(robots), end(robots), [](const robot& r1, const robot& r2) { return distance(r1) < distance(r2); })