mercredi 23 décembre 2015

How C++ set insert work with custom comparator

I am wring one set of pointers

class CLwObj {
private:
string name ;
int type ;

public:
CLwObj() {}
CLwObj(string val, int typ) { name =val ; type = typ; }

string getName() { return name; }
int getType() { return type; }
};

class CLwObjCompare
{
    public:
    bool operator () (CLwObj* obj1, CLwObj* obj2) const
    {
        bool val =  ((obj1->getName().compare(obj2->getName()) < 0) ) ;
        return val;
    }
};

int main ()
{
    set<CLwObj*, CLwObjCompare> myset ;

    CLwObj *obj1 = new CLwObj("hello", 1);
    CLwObj *obj2 = new CLwObj("kello", 1);
    CLwObj *obj3 = new CLwObj("hello", 1);

    myset.insert(obj1);
    myset.insert(obj2);
    myset.insert(obj3);
    return 0;
}

Please explain how insert work with custom comparator , i am getting only two entry since two having same name.

I thought compare function only decided orders.
All object will have different address so 3 entry should be there .

Aucun commentaire:

Enregistrer un commentaire