声明函数对象进行比较?

发布于 2024-08-11 18:48:22 字数 1147 浏览 6 评论 0原文

我见过其他人提出的问题,但没有发现任何问题适用于我在这里想要实现的目标。

我正在尝试使用 std::sort 和 std::vector 通过 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 ,我不知道使用compareByX函数对象时是否会出现问题?

我对 C++ 还很陌生,所以欢迎任何形式的帮助。

I have seen other people questions but found none that applied to what I'm trying to achieve here.

I'm trying to sort Entities via my EntityManager class using std::sort and a std::vector<Entity *>

/*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);
}

I'm getting a dozen of errors like

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

I'm not sure but ENTITY_VECTOR is std::vector<Entity *> , and I don't know if that could be the problem when using the compareByX function object ?

I'm pretty new to C++, so any kind of help is welcome.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

夜空下最亮的亮点 2024-08-18 18:48:23

第三个进来了......编辑问题后,仍然有一个开放的主题:您的比较器将 const & 传递给 GameEntity 类。为了使用 vector 的值,它应该采用 const GameEntity* 参数。

And a third one comes in... After you edited you question, still one open topic: your comparator takes a const & to the GameEntity class. It should, in order to work with the values of the vector<GameEntity*>, take const GameEntity* arguments instead.

临风闻羌笛 2024-08-18 18:48:23

函子是一个定义了operator()的类,因此可以使用与调用函数相同的语法来“调用”该类的对象:

struct functor { 
   bool operator()(Entity const &a, Entity const &b) {
       return a.x < b.x;
   }
};

如果您希望将其作为实体类的成员,则可以使用嵌套类:

class Entity { 
    float x;
public:
    friend class byX;
    class byX {
        bool operator()(Entity const &a, Entity const &b) { 
            return a.x < b.x;
        }
    };
};

那么您的排序将如下所示:

std::sort(ManagedEndities.begin(), ManagedEntities.end(), Entity::byX());

或者,如果您通常按 X 对实体进行排序,则可以定义运算符<对于实体:

class Entity { 
     float x;
public:
     bool operator<(Entity const &other) { 
         return x < other.x;
     }
};

在这种情况下,您对排序的使用会更简单一些:

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

但是,将比较函数创建为实体类的普通成员函数,将导致非常难看的排序调用——它通常需要一些东西像 std::mem_fun_ref 一样完成这项工作;它太丑陋了,我通常会在实际代码中避免使用它。

A functor is a class that defines operator() so an object of that class can be "invoked" with the same syntax as calling a function:

struct functor { 
   bool operator()(Entity const &a, Entity const &b) {
       return a.x < b.x;
   }
};

If you want that as a member of your Entity class, you'd use a nested class:

class Entity { 
    float x;
public:
    friend class byX;
    class byX {
        bool operator()(Entity const &a, Entity const &b) { 
            return a.x < b.x;
        }
    };
};

Then your sort would look something like this:

std::sort(ManagedEndities.begin(), ManagedEntities.end(), Entity::byX());

Alternatively, if you usually sort Entities by X, you could define operator< for Entity:

class Entity { 
     float x;
public:
     bool operator<(Entity const &other) { 
         return x < other.x;
     }
};

In this case, your use of sort would be a bit simpler:

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

Creating the comparison function as a normal member function of the Entity class, however, will lead to a sort invocation that's pretty ugly -- it'll usually need something like std::mem_fun_ref to do the job; it's sufficiently ugly that I'd generally avoid it for real code.

寒冷纷飞旳雪 2024-08-18 18:48:23

不过,最近我确实看到了这个问题......

答案是这样的:提供给 sort 的函数不应该是某个东西的成员函数。含义:它应该是一个静态函数,或者一个自由函数。如果您将其声明为静态函数,您仍应在其前面添加 Entity::compareByX 以便正确命名。

如果您在类本身中定义顺序,则可以像 aJ 所说的那样,使用函数适配器 mem_fun 或 mem_fun_ref 将其倒入“自由”函子对象中。

如果您想要 Entity 对象进行比较,您应该为 sort 提供一个对象(在本例中称为函子或比较器):

struct EntityComp {
  bool operator()( const GameEntity& a, const GameEntity& b ) const { 
    return a.x < b.x;
  }
}


...
std::sort( v.begin(), v.end(), EntityComp() );

I did see this question, recently, though....

The answer was something in the way of: the function provided to sort should not be a member-function of something. Meaning: it should be a static function, or a free function. In case you declare it a static function, you should still precede it by Entity::compareByX in order to name it correctly.

If you define the order in the class itself, you can, as aJ already said, use a function adapter mem_fun or mem_fun_ref to pour it into a 'free' functor object.

If you want an Entity object to do the comparison, you should provide sort with an object (called a functor or comparator in this case):

struct EntityComp {
  bool operator()( const GameEntity& a, const GameEntity& b ) const { 
    return a.x < b.x;
  }
}


...
std::sort( v.begin(), v.end(), EntityComp() );
不美如何 2024-08-18 18:48:23

我相信 compareByX 应该是 static 成员或查看 这里

I believe compareByX should be a static member or lake a look here

神经暖 2024-08-18 18:48:23

根据“您想要实现的目标”,我可能会做另一种猜测...您希望能够指定是否通过对象的 GameEntity::x 成员来比较对象,或者通过他们的 GameEntity::y 成员。

最简单的方法是像您一样为每个成员指定一个函子:

struct CompareX {
   bool operator()( const GameEntity& a, const GameEntity& b ) const {
      return a.x < b.x;
   }
};

struct CompareY {
   bool operator()( const GameEntity& a, const GameEntity& b ) const {
      return a.y < b.y;
   }
};

CompareX compx; // create a compare object
std::sort( v.begin(), v.end(), compx );

“灵活”但更麻烦的方法是创建一个模板函子:

#include <iostream>

using namespace std;

// a mockup of your class
struct GameEntity { float x, y, z; };

// just to be able to print it...
ostream& operator<<( ostream& o, const GameEntity& g ) {
  return o << "(" << g.x << ", " << g.y << ", " << g.z << ")";
}

// cumbersome starts here...
typedef float (GameEntity::*membervar);

// a 'generic' float-member comparator
template< membervar m > struct CompareBy {
   bool operator()( const GameEntity& a, const GameEntity& b ) const {
      return a.*m < b.*m ;
   }
};

// example code
int main() {
   using namespace std;
   GameEntity v[] = { {1,0,0}, {2,0,1}, {3,-1,2} };
   GameEntity* vend = v + sizeof(v)/sizeof(v[0]);

   sort( v, vend, CompareBy< &GameEntity::x >() );
   copy( v, vend, ostream_iterator<GameEntity>( cout, "\n" ) );
}

In the light of 'what you're trying to achieve', I may do another guess... You want to be able to specify whether to compare your objects by their GameEntity::x member, or by their GameEntity::y member.

The easiest way would be to, as you did, specify a functor for each member:

struct CompareX {
   bool operator()( const GameEntity& a, const GameEntity& b ) const {
      return a.x < b.x;
   }
};

struct CompareY {
   bool operator()( const GameEntity& a, const GameEntity& b ) const {
      return a.y < b.y;
   }
};

CompareX compx; // create a compare object
std::sort( v.begin(), v.end(), compx );

The 'flexible' yet more cumbersome way would be to create a template functor:

#include <iostream>

using namespace std;

// a mockup of your class
struct GameEntity { float x, y, z; };

// just to be able to print it...
ostream& operator<<( ostream& o, const GameEntity& g ) {
  return o << "(" << g.x << ", " << g.y << ", " << g.z << ")";
}

// cumbersome starts here...
typedef float (GameEntity::*membervar);

// a 'generic' float-member comparator
template< membervar m > struct CompareBy {
   bool operator()( const GameEntity& a, const GameEntity& b ) const {
      return a.*m < b.*m ;
   }
};

// example code
int main() {
   using namespace std;
   GameEntity v[] = { {1,0,0}, {2,0,1}, {3,-1,2} };
   GameEntity* vend = v + sizeof(v)/sizeof(v[0]);

   sort( v, vend, CompareBy< &GameEntity::x >() );
   copy( v, vend, ostream_iterator<GameEntity>( cout, "\n" ) );
}
明天过后 2024-08-18 18:48:23

试试这个..

 class CompareByX
 {
   operator ()(const GameEntity &a, const GameEntity &b) { ... };
 };

 ...
 std::sort( this->begin(), this->end(), CompareByX);

简而言之,仿函数是一个函数对象 - STL 专门寻找一个接受我指定的两个参数的运算符 ()。如果您是 C++ 新手,我建议您查找运算符和函子 - 即使在 STL 之外,它们也非常方便。

编辑:杰里的答案更好,更全面。

try this..

 class CompareByX
 {
   operator ()(const GameEntity &a, const GameEntity &b) { ... };
 };

 ...
 std::sort( this->begin(), this->end(), CompareByX);

In a nutshell, a functor is a function object - the STL looks specifically for an operator () that takes in the two parameters I've specified. If you're new to C++, I suggest you look up operators and functors - they're pretty handy even outside STL.

Edit: Jerry's answer is better, and more comprehensive.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文