集合集合的重载运算符

Overload operator for set of sets

我只是构建了一个小程序来了解它是如何工作的,因为我需要它来做一些更困难的事情,但我做不到。

我想我需要定义运算符重载,但我不知道如何定义,因为它们是 set<set<a>>

的两个对象

如果你编译你会看到一个很大的错误,它注意到他无法比较 myset == myset2 我认为它会对运算符 !==[= 说同样的话15=]

#include <set>
using namespace std;

class a{
private:
     int a_;
public:
    int get_a() const{ return a_; }
     void set_a(int aux){ a_=aux;}
     bool operator < (const a& t) const{
         return this->get_a() < t.get_a();
     }
};


class b{
private:
     set<set<a> > b_;
public:
     void set_(set<a> aux){ b_.insert(aux); }
     //Overload operators?
};


int main(){
    b myset;    
    b myset2;

    set<a> subset1;
    set<a> subset2;

    a myint;

    myint.set_a(1);
    subset1.insert(myint);

    myint.set_a(2);
    subset1.insert(myint);

    myint.set_a(3);
    subset1.insert(myint);

    myint.set_a(5);
    subset2.insert(myint);

    myint.set_a(6);
    subset2.insert(myint);

    myint.set_a(7);
    subset2.insert(myint);

    myset.set_(subset1);
    myset.set_(subset2);

    myset2.set_(subset1);
    myset2.set_(subset2);


    if(myset == myset2){
        cout << "They are equal" << endl;
    }

    if(myset != myset2){
        cout << "They are different" << endl;
    }

    b myset3;

    myset3 = myset2; //Copy one into other

}

编译器默认不生成运算符(默认的operator=(const T&)operator=(T&&)除外)。您应该明确定义它们:

class b{
private:
     set<set<a> > b_; 
public:
     void set_(set<a> aux){ b_.insert(aux); }
     //Overload operators?

     bool operator==(const b& other) const {
         return b_ == other.b_;
     }

     bool operator!=(const b& other) const {
         return b_ != other.b_;
     } 
};

但是,仅此并不能解决问题。尽管已经为 std::set<T> 定义了比较运算符,但它们仅在存在 T 的运算符时才有效。所以,在这种情况下,你必须为你的 a class 定义 operator==operator!=,就像我用 b [=23] 给你展示的一样=].

为了让您的代码正常工作,您需要指定以下运算符(注意:它们不是默认创建的)

class a{
private: 
     int a_;
public: 
    int get_a() const{ return a_; }
    void set_a(int aux){ a_=aux;}

    /* needed for set insertion */
    bool operator < (const a& other) const {
        return this->get_a() < other.get_a();
    }

    /* needed for set comparison */
    bool operator == (const a& other) const {
        return this->get_a() == other.get_a();
    }
};



class b{
private:
     set<set<a> > b_;
public:
     void set_(set<a> aux){ b_.insert(aux); }

     /* needed, because myset == myset2 is called later in the code */
     bool operator == (const b& other) const {
        return this->b_ == other.b_;
     }

     /* needed, because myset != myset2 is called later in the code */
     bool operator != (const b& other) const {
        return !(*this == other);
     }
};

您还应该看看 http://en.cppreference.com/w/cpp/container/set 并了解其他运算符 std::set 在其元素上内部使用的内容。