Vallabh Patade
Vallabh Patade

Reputation: 5110

C++ container - set and object

I have following class.

class Student {   
    //Parameterized constructor.
    private:
       int rollNo;
       char* name;
       float marks;
 }

I have a set<Student> students. When I insert a student object in set, how can I sepcify that two objects are same. E.g. I am considering two objects same if their rollNo is same so Student s1(10,"ABC",35) and Student s2(10,"XYZ",67) both are same. So when I say students.insert(s1) and students.insert(s2), set will have only one object i.e. s1.

Upvotes: 0

Views: 122

Answers (3)

igleyy
igleyy

Reputation: 605

You need to declare and define friend operator> for class Student

Example code

class Student {
  /* everything you already have */
  public:
  friend bool operator<(const Student& lhs, const Student& rhs);
};

bool operator<(const Student& lhs, const Student& rhs) {
  return lhs.rollNo < rhs.rollNo;
}

Solution provided thermite does not work because compare function doesn't have access to private members of class Student. To solve this problem, you can declare operator< as friend. A friend function (or class) can access the private and protected members of the class in which it is declared as a friend.

Upvotes: 0

RnR
RnR

Reputation: 2115

The way I do this is just define the less then operator - if neither of two elements is less then the other then they are effectively equal/equivalent to each other - the "original" thread linked by Daniel shows this nicely.

Upvotes: 0

thermite
thermite

Reputation: 512

I've never done this in c++ but a quick look at http://www.cplusplus.com/reference/set/set/set/ explains it nicely. Basically when you instantiate the set you need to give it a comparison object which " returns true if the first argument goes before the second argument"

for ints it could be

struct classcomp {
  bool operator() (const int& lhs, const int& rhs) const
  {return lhs<rhs;}
};

in your case that would be more like

struct StudentCompare{
    bool operator() (const Student& lsh, const Student& rhs) const
    {
        return lhs.rollNo < rhs.rollNo; //or however they need to be compared
    }
};

and then you can instantiate it like

std::set<int,StudentCompare> mySet;

This wont work as is for your code as rollNo is private. I recommend that you read the page i linked to above to better understand is going on.

Upvotes: 1

Related Questions