I decided to practice writing code in C ++, and that's what I got in the context of your question. I relied on your previous question, where you gave the definition of the list structure and some of its methods.
#include <iostream> #include <cstring> #include <utility> #include <initializer_list> class List { public: enum SortType { SortByName, SortByAge }; typedef std::pair<const char *, unsigned int> Human; public: List() = default; List(const List &) = delete; List & operator =(const List &) = delete; ~List() { while (head) { Person *tmp = head; head = head->next; delete[] tmp->name; delete tmp; } } void push(const char *name, unsigned int age) { push({ name, age }); } void push(const Human &h ) { char *s = new char[std::strlen(h.first) + 1]; std::strcpy(s, h.first); head = new Person{ s, h.second, head }; } std::ostream & show(std::ostream &os = std::cout) const { for (Person *current = head; current; current = current->next) { os << current->name << ' ' << current->age << std::endl; } return os; } void sort(SortType type = SortByName) { bool ( *order_by[2] )( const Human &, const Human & ) = { []( const Human &h1, const Human &h2) { int res = std::strcmp(h1.first, h2.first); return res < 0 || (res == 0 && h1.second < h2.second); }, [](const Human &h1, const Human &h2) { int res = std::strcmp(h1.first, h2.first); return h1.second < h2.second || ( h1.second == h2.second && res < 0); } }; if (type != SortByAge) type = SortByName; for (Person *current = head; current; current = current->next) { for (Person *next = current->next; next; next = next->next) { if (order_by[type](Human(next->name, next->age), Human(current->name, current->age))) { std::swap(current->name, next->name); std::swap(current->age, next->age); } } } } private: struct Person { const char *name; unsigned int age; Person *next; }; Person *head = nullptr; }; int main() { List lst; for (const auto &h : std::initializer_list<List::Human>( { { "Petr", 21 }, { "Ann", 26 }, { "Bob", 24 }, { "Kate", 24 } } ) ) { lst.push(h); } lst.show() << std::endl; lst.sort(); lst.show() << std::endl; lst.sort(List::SortByAge); lst.show() << std::endl; }
The output of the program to the console is as follows:
Kate 24 Bob 24 Ann 26 Petr 21 Ann 26 Bob 24 Kate 24 Petr 21 Petr 21 Bob 24 Kate 24 Ann 26