【问题标题】:Sorting a map of objects C++对对象图进行排序 C++
【发布时间】: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&amp; r1, const robot&amp; r2) { return distance(r1) &lt; distance(r2); })

标签: c++ sorting vector


【解决方案1】:

是的,有std::sort,它将根据任何适当的关系进行排序:

std::sort(robots.begin(), 
          robots.end(),
          [](const robot& lhs, const robot& rhs) 
            { return distance(lhs) < distance(rhs); });

或者,如果你想要一个可重用的谓词:

bool closer(const robot& r1, const robot& r2)
{
    return distance(r1) < distance(r2);
}

// ...
std::sort(robots.begin(), robots.end(), closer);

也可以重载&lt; 运算符,然后说

std::sort(robots.begin(), robots.end());

但是,当您的对象可以有意义地称为“小于”彼此并且您在其他情况下也想要&lt; 时,这更有意义。

【讨论】:

  • 感谢您的帮助。
猜你喜欢
  • 2021-09-16
  • 1970-01-01
  • 2013-12-05
  • 2021-11-18
  • 2010-10-29
  • 2012-02-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多