From ed6e8e2116d4fe7a3dca418e40c9af83cc8e3abf Mon Sep 17 00:00:00 2001 From: Jidong Xiao Date: Fri, 9 Feb 2024 13:43:31 -0500 Subject: [PATCH] adding the list sort example --- lectures/09_iterators_linked_lists/README.md | 33 +++++++++++++++++++ .../09_iterators_linked_lists/list_sort.cpp | 27 +++++++++++++++ 2 files changed, 60 insertions(+) create mode 100644 lectures/09_iterators_linked_lists/list_sort.cpp diff --git a/lectures/09_iterators_linked_lists/README.md b/lectures/09_iterators_linked_lists/README.md index 7bd807b..03eaea9 100644 --- a/lectures/09_iterators_linked_lists/README.md +++ b/lectures/09_iterators_linked_lists/README.md @@ -118,6 +118,39 @@ compare function as STL vector. The value of any associated vector iterator must be re-assigned / re-initialized after these operations. +### List Sort Example + +The following [example](list_sort.cpp) demonstrate how to call the list sort function. + +```cpp +#include +#include + +int main() { + // Create a list of integers + std::list numbers = {5, 2, 9, 3, 7}; + + // Print the original list + std::cout << "Original list: "; + for (int num : numbers) { + std::cout << num << " "; + } + std::cout << std::endl; + + // Sort the list in ascending order + numbers.sort(); + + // Print the sorted list + std::cout << "Sorted list: "; + for (int num : numbers) { + std::cout << num << " "; + } + std::cout << 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.cpp b/lectures/09_iterators_linked_lists/list_sort.cpp new file mode 100644 index 0000000..84507dc --- /dev/null +++ b/lectures/09_iterators_linked_lists/list_sort.cpp @@ -0,0 +1,27 @@ +#include +#include + +int main() { + // Create a list of integers + std::list numbers = {5, 2, 9, 3, 7}; + + // Print the original list + std::cout << "Original list: "; + for (int num : numbers) { + std::cout << num << " "; + } + std::cout << std::endl; + + // Sort the list in ascending order + numbers.sort(); + + // Print the sorted list + std::cout << "Sorted list: "; + for (int num : numbers) { + std::cout << num << " "; + } + std::cout << std::endl; + + return 0; +} +