是否可以将class方法作为比较器?

Is it possible to take the class method as comparator?

我在级别 class 中有一个私有比较器:

   bool positionCmp(Entity* a, Entity* b);

当我尝试在另一个级别 class 方法中使用它时:

void Level::drawEntities(std::vector<Entity*> entities)
{
    sort(entities.begin(), entities.end(), positionCmp);
    for (int i = 0; i < entities.size(); ++i) entities[i]->draw();
}

Visual Studio 2019 编译器说: 'Level::positionCmp': non-standard syntax; use '&' to create a pointer to member。 如果我添加“&”,我会得到 '&': illegal operation on bound member function expression

void Level::drawEntities(std::vector<Entity*> entities)
    {
        sort(entities.begin(), entities.end(), &positionCmp);
        for (int i = 0; i < entities.size(); ++i) entities[i]->draw();
    } 

我该怎么办?

你需要这样的东西:

std::sort(entities.begin(), entities.end(),
  [this](Entity* a, Entity* b) { return positionCmp(a, b); });

这假设 positionCmp 实际上引用了 Level 的一些数据成员,并且需要访问 Level 实例来完成它的工作。如果不是——如果它只需要两个 Entity 个实例作为参数传递——然后将其声明为静态的,如

static bool positionCmp(Entity* a, Entity* b);

然后您的原始版本 sort(entities.begin(), entities.end(), positionCmp) 将按原样运行。

声明成员函数 static,并使用任一语法。

class Level 中的成员函数 bool positionCmp(Entity* a, Entity* b); 实际上有第三个隐含类型为 Level* 的参数用于 this 指针,即使定义实际上并没有使用 thisthis 的任何成员。因此,如果没有“当前对象”的参数就不能调用它 - 通过 level.positionCmp(a, b)p->positionCmp(a, b) 表达式,或者在另一个非静态成员函数中使用隐含的 this->positionCmp(a, b) Level 或派生的 class.

static 关键字表示该函数不需要 this 对象,因此该函数可以像您预期的那样充当普通的双参数函数。