0

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

 #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;
}

输出:

实体[0]:编号:2

实体[1]:编号:1

实体[2]:编号:4

实体[3]:编号:3

我希望得到以下输出:

实体[1]:编号:1

实体[0]:编号:2

实体[3]:编号:3

实体[2]:编号:4

4

1 回答 1

0

您需要取消引用您的指针*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;
}

演示

于 2019-11-01T00:21:43.347 回答