Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I am asked to create a multiset to hold pointers to person objects and to define

ID: 3576608 • Letter: I

Question

I am asked to create a multiset to hold pointers to person objects and to define the multiset with comparePersons function object which will sort automatically by names of the person. I have to put them into a multiset and display the contents.
The problem I am having is that I am unable to sort the multiset and I am not sure why it isn't working. I get an error when I call sort.This is the code I have so far.

// function object to compare persons using pointers
class comparePersons
{
public:
   bool operator() (const person* ptrP1, const person* ptrP2) const
   {
       return *ptrP1 < *ptrP2;
   }
};

in my main...

person* ptrP1 = new person( "Angel", "Bruce", 12345);
person* ptrP2 = new person( "Luis", "Lopez", 45678);
person* ptrP3 = new person( "Andrea", "Stacey", 6789);
person* ptrP4 = new person( "Cat", "William", 12345);
person* ptrP5 = new person( "Angel", "Bruce", 55345);
person* ptrP6 = new person( "Jason", "Lee", 197645);


   //Creating multiset
   multiset<person*> multiPtrsPers;
   multiPtrsPers.insert(ptrP1);
   multiPtrsPers.insert(ptrP2);
   multiPtrsPers.insert(ptrP3);
   multiPtrsPers.insert(ptrP4);
   multiPtrsPers.insert(ptrP5);
   multiPtrsPers.insert(ptrP6);

   for_each(multiPtrsPers.begin(),multiPtrsPers.end(), displayPerson());//display person
   cout << endl;

   sort(multiPtrsPers.begin(), multiPtrsPers.end(), comparePersons());//compare persons

   for_each(multiPtrsPers.begin(), multiPtrsPers.end(), displayPerson());//display persons
   cout << endl;

Explanation / Answer

class comparePersons
{
public:
   bool operator() (const person* ptrP1, const person* ptrP2) const
   {
       return *ptrP1 < *ptrP2;
   }
};

int main() {

person* ptrP1 = new person( "Angel", "Bruce", 12345);
person* ptrP2 = new person( "Luis", "Lopez", 45678);
person* ptrP3 = new person( "Andrea", "Stacey", 6789);
person* ptrP4 = new person( "Cat", "William", 12345);
person* ptrP5 = new person( "Angel", "Bruce", 55345);
person* ptrP6 = new person( "Jason", "Lee", 197645);


   //Creating multiset
   multiset<person*> multiPtrsPers;
   multiPtrsPers.insert(ptrP1);
   multiPtrsPers.insert(ptrP2);
   multiPtrsPers.insert(ptrP3);
   multiPtrsPers.insert(ptrP4);
   multiPtrsPers.insert(ptrP5);
   multiPtrsPers.insert(ptrP6);

   for_each(multiPtrsPers.begin(),multiPtrsPers.end(), displayPerson());//display person
   cout << endl;

   sort(multiPtrsPers.begin(), multiPtrsPers.end(), comparePersons());//compare persons

   for_each(multiPtrsPers.begin(), multiPtrsPers.end(), displayPerson());//display persons
   cout << endl;

}