shizaero

Help

Jan 11th, 2023
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.15 KB | None | 0 0
  1. #include <algorithm>
  2. #include <iostream>
  3. #include <vector>
  4.  
  5. using namespace std;
  6.  
  7. struct Animal {
  8.     string name;
  9.     int age;
  10.     double weight;
  11. };
  12.  
  13. template <typename Container, typename KeyMapper>
  14. void SortBy(Container& container, KeyMapper key_mapper, bool reverse = false) {
  15.     sort(container.begin(), container.end(),
  16.         [key_mapper, &reverse](const auto& rhs, const auto& lhs) {
  17.             return (reverse && key_mapper(lhs) > key_mapper(rhs)) || (key_mapper(lhs) < key_mapper(rhs));
  18.         });
  19. }
  20.  
  21. void PrintNames(const vector<Animal>& animals) {
  22.     for (const Animal& animal : animals) {
  23.         cout << animal.name << ' ';
  24.     }
  25.     cout << endl;
  26. }
  27.  
  28. int main() {
  29.     vector<Animal> animals = {
  30.         {"Мурка"s, 10, 5},
  31.         {"Белка"s, 5, 1.5},
  32.         {"Георгий"s, 2, 4.5},
  33.         {"Рюрик"s, 12, 3.1},
  34.     };
  35.  
  36.     PrintNames(animals);
  37.  
  38.     SortBy(animals, [](const Animal& animal) {
  39.         return animal.name;
  40.         });
  41.     PrintNames(animals);
  42.  
  43.     SortBy(animals, [](const Animal& animal) {
  44.         return -animal.weight;
  45.         });
  46.     PrintNames(animals);
  47.  
  48.     return 0;
  49. }
Advertisement
Add Comment
Please, Sign In to add comment