c++ - 根据非静态值对结构进行排序 (C++)

标签 c++ sorting std

我有一个 EnemyRhombus 类。它是一个单位,可以移动到 map 上的不同点。

我想按照与它们的距离增加的顺序处理它可以移动到的点。

为此,我想对这些点进行排序。

代码 1:

class EnemyRhombus
{
public:
    int x,y;
    int dist(Point p)
    {
        int dx=abs(p.x-x);
        int dy=abs(p.y-y);
        return dx+dy-min(dx,dy);
    }
    bool points_cmp(Point f, Point s)
    {
        return dist(f)<dist(s);
    }
    void move()
    {
        vector<Point> candidates;
        //...
        sort(candidates.begin(),candidates.end(),points_cmp);
    }
}

不编译。版画

[错误] 没有匹配函数来调用 'sort(std::vector::iterator, std::vector::iterator, )'

代码 2:

class EnemyRhombus
{
public:
    int x,y;
    static int dist(Point p, int tx, int ty)
    {
        int dx=abs(p.x-tx);
        int dy=abs(p.y-ty);
        return dx+dy-min(dx,dy);
    }
    template<int X, int Y> static bool points_cmp(Point f, Point s) 
    {
        return dist(f,X,Y)<dist(s,X,Y);
    }
    void move()
    {
        vector<Point> candidates;
        //...
        sort(candidates.begin(),candidates.end(),points_cmp<x,y>);
    }
}

产生错误:

[错误] 'EnemyRhombus::x' 不能出现在常量表达式中

[错误] 'EnemyRhombus::y' 不能出现在常量表达式中


我该如何解决这个问题?


使用答案中的示例可能会产生错误和警告,说默认情况下启用 c++ 11,这是不正确的(至少在 orwell dev-cpp 中)。 为了使它们工作,应该将 -std=c++11 添加到编译器命令中。 (在我的例子中,工具->编译器选项-> Genera)

最佳答案

除了使用静态/类外函数或使用 P0W 建议的方法之外,您还可以使用 C++11 lambda。

std::sort(candidates.begin(),candidates.end(),
    [&](Point f, Point s) { return dist(f) < dist(s); }
);

lambda 负责排序的顺序。

关于c++ - 根据非静态值对结构进行排序 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28434944/

相关文章:

c++ - 将 LAPACK 安装到 Visual Studio 2015

javascript - 将 HashString 从 C 转换为 JS

sql - 子查询和排序? (排序依据)

c++ - 在 C++ 中使用 C 头文件时,我们应该使用 std::或全局命名空间中的函数吗?

c++ - 使用 move 从 vector 构造对象

c++ - 在自定义 boost 日志格式函数中格式化范围属性

c++ - 在 C++ 中显式声明默认方法

Python:在比较它们之前我需要对字典进行排序吗?

objective-c - 使用给定语言环境创建 NSSortDescriptor

c++ - C风格数组的标准容器