对于指向 std::set 容器中的用户定义 class 的指针,自定义比较 class 无法正常工作

Custom compare class not working as I expect for pointers to a user defined class in a std::set container

我不明白为什么在此代码示例中,std::set 容器没有根据我定义的比较 class 对实体进行排序。任何人都可以帮助我吗?谢谢

 #include <iostream>
 #include <set>

 class Entity {
 public:
 int num;
 Entity(int num):num(num){}
     bool operator< (const Entity& _entity) const { return (this->num < _entity.num); }
 };

 struct my_cmp {
     bool operator() (const Entity* lhs, const Entity* rhs) const { return (lhs < rhs); }
 };

 class EntityManager {
     private:
        std::set<Entity*, my_cmp> entities;
   public:
        void AddEntity(int num) { entities.insert(new Entity(num)); }
        void ListAllEntities() const {
              unsigned int i = 0; 
              for (auto& entity: entities) {
                  std::cout << "Entity[" << i << "]: num:" << entity->num << std::endl;
                  i++;
              }
         }
};

int main(void) {
    EntityManager manager;
    manager.AddEntity(2);
    manager.AddEntity(1);
    manager.AddEntity(4);
    manager.AddEntity(3);
    manager.ListAllEntities();
    return 0;
}

输出:

Entity[0]: num:2

Entity[1]: num:1

Entity[2]: num:4

Entity[3]: num:3

我希望得到以下输出:

Entity[1]: num:1

Entity[0]: num:2

Entity[3]: num:3

Entity[2]: num:4

您需要取消引用您的指针 *lhs < *rhs。您只是比较当前指针的值,因此您的顺序取决于它们在内存中的位置。

#include <iostream>
 #include <set>

 class Entity {
 public:
 int num;
 Entity(int num):num(num){}
     bool operator< (const Entity& _entity) const { return (this->num < _entity.num); }
 };

 struct my_cmp {
     bool operator() (const Entity* lhs, const Entity* rhs) const { return (*lhs < *rhs); }
 };

 class EntityManager {
     private:
        std::set<Entity*, my_cmp> entities;
   public:
        void AddEntity(int num) { entities.insert(new Entity(num)); }
        void ListAllEntities() const {
              unsigned int i = 0; 
              for (auto& entity: entities) {
                  std::cout << "Entity[" << i << "]: num:" << entity->num << std::endl;
                  i++;
              }
         }
};

int main(void) {
    EntityManager manager;
    manager.AddEntity(2);
    manager.AddEntity(1);
    manager.AddEntity(4);
    manager.AddEntity(3);
    manager.ListAllEntities();
    return 0;
}

Demo