0

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.

Vallabh Patade
  • 4,960
  • 6
  • 31
  • 40
  • 1
    possible duplicate of [std::set with user defined type, how to ensure no duplicates](http://stackoverflow.com/questions/1114856/stdset-with-user-defined-type-how-to-ensure-no-duplicates) – Daniel Frey Nov 13 '13 at 21:12

3 Answers3

1

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.

thermite
  • 502
  • 6
  • 19
0

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.

RnR
  • 2,096
  • 1
  • 15
  • 23
0

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.

igleyy
  • 605
  • 4
  • 16