jean jean - 1 month ago 19
C++ Question

Overload operator for set of sets

I just build a mini program to understand how this will work because i need this for something a bit more difficult but i can't make this work.

I think i need to define operator overload but i dont know how because they are two objects of

set<set<a>>


If you compile you will see a big error where it notice that he can't compare
myset == myset2
and i think it will say same for operator
!=
and
=


#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

}

Answer

In order for your code to work you need to specify following operators (note: they are not created by default)

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

You should also take a look at http://en.cppreference.com/w/cpp/container/set and see what other operators std::set uses internally on its elements.