Chapter 18 - Worked Exercises 1

Exercise 1 - Birthday Sort

You are provided with the following class definition for Person

struct Date {
    int day;
    int month;
    int year;
};

struct Person {
    std::string name;
    Date birthday;    
};

Each Person has a string member variable called name representing the name of the person, and a member variable of type Date called birthday representing the birthday of the person.

Part 0

Create three instances of Person with names "Alice", "Bob", and "Charlie", with some birthdates of your choice.

Add each of them to an std::list.

Part 1

Implement the operator< function for the Date class to allow comparisons between two dates.

date1 < date2 should return true if date1 is a date that comes before date2.

Write three test functions for the below three cases testing the operator< function you've created:

  • When date1 and date2 are the same date

  • When date1 comes before date2

  • When date1 comes after date2

Part 2

Implement a binary predicate that will be used to sort the list you created in Part 0. The binary predicate should compare between two instances of Person, with the intension of sorting an std::list<Person> in ascending order of birthdates.

bool SortPeople(const Person& lhs, const Person& rhs) {
    // ...
}

personList.sort(SortPeople);

Last updated

Was this helpful?