Advertisement
Alaricy

спринт2 урок6 2/3

Oct 31st, 2022 (edited)
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.13 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 reverce=false) {
  15. sort(container.begin(), container.end(),
  16.         [key_mapper, reverce](const auto& lhs, const auto& rhs) {
  17.           if (reverce) return key_mapper(lhs) > key_mapper(rhs);
  18.           else  return key_mapper(lhs) < key_mapper(rhs);
  19.         });
  20. }
  21.  
  22. void PrintNames(const vector<Animal>& animals) {
  23.     for (const Animal& animal : animals) {
  24.         cout << animal.name << ' ';
  25.     }
  26.     cout << endl;
  27. }
  28.  
  29. int main() {
  30.     vector<Animal> animals = {
  31.         {"Мурка"s,   10, 5},
  32.         {"Белка"s,   5,  1.5},
  33.         {"Георгий"s, 2,  4.5},
  34.         {"Рюрик"s,   12, 3.1},
  35.     };
  36.     PrintNames(animals);
  37.     SortBy(animals, [](const Animal& animal) { return animal.name; }, true);
  38.     PrintNames(animals);
  39.     SortBy(animals, [](const Animal& animal) { return animal.weight; });
  40.     PrintNames(animals);
  41.     return 0;
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement