c++ - 声明用于比较的函数对象?

标签 c++ operators operator-keyword function-object

我看过其他人的问题,但没有找到适用于我在这里要实现的目标的问题。

我正在尝试使用 std::sort 和 std::vector<Entity *> 通过我的 EntityManager 类对实体进行排序

/*Entity.h*/
class Entity
{
public:
 float x,y;
};

struct compareByX{
 bool operator()(const GameEntity &a, const GameEntity &b)
 {
  return (a.x < b.x);
 }
};   
   
/*Class EntityManager that uses  Entitiy*/

typedef std::vector<Entity *> ENTITY_VECTOR; //Entity reference vector
   
class EntityManager: public Entity
{
private:
 ENTITY_VECTOR managedEntities;

public:
 void sortEntitiesX();
};

void EntityManager::sortEntitiesX()
{
 
 /*perform sorting of the entitiesList by their X value*/
 compareByX comparer;
 
 std::sort(entityList.begin(), entityList.end(), comparer);
}

我遇到了很多错误,例如

: error: no match for call to '(compareByX) (GameEntity* const&, GameEntity* const&)'
: note: candidates are: bool compareByX::operator()(const GameEntity&, const GameEntity&)

我不确定,但 ENTITY_VECTOR 是 std::vector<Entity *> ,我不知道在使用 compareByX 函数对象时是否会出现问题?

我是 C++ 的新手,所以欢迎任何形式的帮助。

最佳答案

第三个进来了......在你编辑你的问题之后,仍然是一个开放的话题:你的比较器需要一个 const &GameEntity类(class)。它应该,以便与 vector<GameEntity*> 的值一起工作, 取 const GameEntity*参数代替。

关于c++ - 声明用于比较的函数对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1765539/

相关文章:

c++ - 列表初始化的复制省略,它在标准中的何处规定?

c++ - 简单的 C++ 运算符重载帮助

Ruby 无法识别 "^="运算符

c++ - 如何计算当月的星期日?

C++将数组参数传递给函数

c++ - 标识符 "ostream"是未定义的错误

c++ - 运算符 << 重载

c++ - 运算符重载 [][] 二维数组 C++

c++ - Eclipse CDT 移动文件和重命名文件重构?

templates - Twig:否定包含运算符 IN