设置 (c++) 和运算符 < 重载

set (c++) and operator < overload

我有一些 classes,例如一个是这样的:

class foo {

    private:
        int number;
        ...

    public:

        foo(int set_number):number(set_number) {}
        ...

        bool operator<(const foo &myfoo) const
        { 
            return (number < myfoo.number ? 1 : 0); 
        }
        /* operator < */

        bool operator==(const foo &myfoo) const
        { 
             return (number == myfoo.number ? 1 : 0); 
        }
        /* operator == */

        ...
};

我使用的是与此类似的东西 class 和 set:

class hello {
    private:
        set<foo*> list;
        set<int>  int_list;
        ...
    public:
        ...
        fillList(void)
        {
           for(int i=0; i<10; i++)
           {
              list.insert(new foo(i));
              int_list.insert(i);
           }
        }
        ...
};

好的,所以当我打印结果时,我得到:

int_list: 0, 1, 2, 3, 4, ... 
list: 0, 6, 4, 5, ... (Using a method to print the attribute "number" from the object foo).

显然第二个不行。我想这与集合是由指针而不是对象组成的事实有关。

现在,我应该像 set 一样使用我的 set 吗?或者是否有使用指针的解决方案?也许我可以使用类似的东西重载运算符:

bool operator<(const *foo myvar, const *foo myvar2); 

我正在使用这个 "set< foo* >"。因为有人教我在vector对象中使用这种方式。

最好的选择是什么?

如果您想在集合中进行自定义排序,则不能覆盖 < 运算符,因为:

set<foo*>

它是一组指针。改用:

set<foo*, compare>

并且:

struct compare {
    bool operator() (const foo * lhs, const foo * rhs) const{
        return lhs->operator<(*rhs);
    }
};

原因

你的集合正在排序指针。如果将 compare 添加到 set<foo*, compare>,则强制使用指向 class 的 < operator

不使用指针的替代方案

只需使用 set<foo> 并从 list.insert(new foo(i)); 中删除新的。