W_A_S_A_B_I
Mar 18th, 2023
46
2
Never
This is comment for paste Задача 2
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <algorithm>
  2. #include <iostream>
  3. #include <vector>
  4. #include <string>
  5.  
  6. using namespace std;
  7.  
  8. struct Animal {
  9.     string name;
  10.     int age;
  11.     double weight;
  12. };
  13.  
  14. template <typename Container, typename KeyMapper>
  15. void SortBy(Container& container, KeyMapper key_mapper, bool reverse = false) {
  16.     sort(container.begin(), container.end(), [key_mapper, reverse](const auto& lhs, const auto& rhs) {
  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.     PrintNames(animals);
  36.     SortBy(animals, [](const Animal& animal) { return animal.name; }, true);
  37.     PrintNames(animals);
  38.     SortBy(animals, [](const Animal& animal) { return animal.weight; });
  39.     PrintNames(animals);
  40.     return 0;
  41. }
Advertisement
Add Comment
Please, Sign In to add comment