Advertisement
chevengur

СПРИНТ № 2 | Шаблоны функции | Урок 6: Функциональные объекты 2/3

Oct 28th, 2023
285
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.16 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 target = false) {
  15.     sort(container.begin(), container.end(), [key_mapper, target](const auto& lhs, const auto& rhs) {
  16.         if (target) {
  17.             return key_mapper(lhs) > key_mapper(rhs);
  18.         }
  19.         return key_mapper(lhs) < key_mapper(rhs);
  20.         });
  21.  
  22. }
  23.  
  24. void PrintNames(const vector<Animal>& animals) {
  25.     for (const Animal& animal : animals) {
  26.         cout << animal.name << ' ';
  27.     }
  28.     cout << endl;
  29. }
  30.  
  31. int main() {
  32.     setlocale(0, "");
  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.     PrintNames(animals);
  40.     SortBy(animals, [](const Animal& animal) { return animal.name; }, true);
  41.     PrintNames(animals);
  42.     SortBy(animals, [](const Animal& animal) { return animal.weight; });
  43.     PrintNames(animals);
  44.     return 0;
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement