集合的集合的重载操作符

Overload operator for set of sets

本文关键字:集合 操作符 重载      更新时间:2023-10-16

我只是建立了一个小程序来了解这将如何工作,因为我需要这个东西有点困难,但我不能使这个工作。

我认为我需要定义操作符重载,但我不知道如何,因为它们是set<set<a>>的两个对象

如果你编译你会看到一个很大的错误,它注意到他不能比较myset == myset2,我想它会说同样的操作符!==

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

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

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在其元素上内部使用了哪些其他操作符。

编译器默认不生成操作符(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操作符的情况下,比较操作符才有效。因此,在本例中,您必须按照与b类相同的方式为a类定义operator==operator!=