shushus

Спринт 2. Функциональные объекты. Задание 2.

Dec 8th, 2022
169
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.38 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, const bool& reverse=false) {
  15.     // теперь можно сортировать контейнер
  16.     // с компаратором key_mapper(lhs) < key_mapper(rhs)
  17.     if(reverse){
  18.         sort(container.begin(), container.end(), [key_mapper](const auto& lhs, const auto& rhs) {return key_mapper(lhs) > key_mapper(rhs);} );
  19.     }else{
  20.     sort(container.begin(), container.end(), [key_mapper](const auto& lhs, const auto& rhs) {return key_mapper(lhs) < key_mapper(rhs);} );
  21.     }
  22.    
  23. }
  24.  
  25. void PrintNames(const vector<Animal>& animals) {
  26.     for (const Animal& animal : animals) {
  27.         cout << animal.name << ' ';
  28.     }
  29.     cout << endl;
  30. }
  31.  
  32. int main() {
  33.     vector<Animal> animals = {
  34.         {"Мурка"s, 10, 5},
  35.         {"Белка"s, 5, 1.5},
  36.         {"Георгий"s, 2, 4.5},
  37.         {"Рюрик"s, 12, 3.1},
  38.     };
  39.  
  40.     PrintNames(animals);
  41.  
  42.     SortBy(animals, [](const Animal& animal) {
  43.         return animal.name;
  44.     });
  45.     PrintNames(animals);
  46.  
  47.     SortBy(animals, [](const Animal& animal) {
  48.         return -animal.weight;
  49.     });
  50.     PrintNames(animals);
  51.  
  52.     return 0;
  53. }
Advertisement
Add Comment
Please, Sign In to add comment