Advertisement
chevengur

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

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