diff --git a/lectures/09_iterators_linked_lists/README.md b/lectures/09_iterators_linked_lists/README.md index 93cd44c..97003fe 100644 --- a/lectures/09_iterators_linked_lists/README.md +++ b/lectures/09_iterators_linked_lists/README.md @@ -151,6 +151,57 @@ int main() { } ``` +### List Sort Example - Sorting Class Objects + +The following [example](list_sort_objects.cpp) demonstrates how to call the list sort function to sort a list which contains class objects. + +```cpp +#include +#include +#include + +// Define a simple class representing a person +class Person { +public: + std::string name; + int age; + + // Constructor + Person(std::string name, int age) : name(name), age(age) {} +}; + +// Custom comparison function to sort Person objects by age +bool compareByAge(const Person& p1, const Person& p2) { + return p1.age < p2.age; +} + +int main() { + // Create a list of Person objects + std::list people = { + {"Alice", 25}, + {"Bob", 30}, + {"Charlie", 20} + }; + + // Print the original list + std::cout << "Original list:" << std::endl; + for (const auto& person : people) { + std::cout << person.name << " (" << person.age << ")" << std::endl; + } + + // Sort the list of Person objects using the custom comparison function + people.sort(compareByAge); + + // Print the sorted list + std::cout << "\nSorted list:" << std::endl; + for (const auto& person : people) { + std::cout << person.name << " (" << person.age << ")" << std::endl; + } + + return 0; +} +``` + ## 9.7 Erase & Iterators STL lists and vectors each have a special member function called erase. In particular, given list of ints s, diff --git a/lectures/09_iterators_linked_lists/list_sort_objects.cpp b/lectures/09_iterators_linked_lists/list_sort_objects.cpp new file mode 100644 index 0000000..77ba4f3 --- /dev/null +++ b/lectures/09_iterators_linked_lists/list_sort_objects.cpp @@ -0,0 +1,45 @@ +#include +#include +#include + +// Define a simple class representing a person +class Person { +public: + std::string name; + int age; + + // Constructor + Person(std::string name, int age) : name(name), age(age) {} +}; + +// Custom comparison function to sort Person objects by age +bool compareByAge(const Person& p1, const Person& p2) { + return p1.age < p2.age; +} + +int main() { + // Create a list of Person objects + std::list people = { + {"Alice", 25}, + {"Bob", 30}, + {"Charlie", 20} + }; + + // Print the original list + std::cout << "Original list:" << std::endl; + for (const auto& person : people) { + std::cout << person.name << " (" << person.age << ")" << std::endl; + } + + // Sort the list of Person objects using the custom comparison function + people.sort(compareByAge); + + // Print the sorted list + std::cout << "\nSorted list:" << std::endl; + for (const auto& person : people) { + std::cout << person.name << " (" << person.age << ")" << std::endl; + } + + return 0; +} +