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
date1anddate2are the same dateWhen
date1comes beforedate2When
date1comes afterdate2
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?