Advertisement
chevengur

СПРИНТ № 7 | Модель памяти в C++ | Урок 4: Указатели и константность

Apr 15th, 2024
744
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 4.89 KB | None | 0 0
  1. #include <algorithm>
  2. #include <cassert>
  3. #include <iostream>
  4. #include <string>
  5. #include <tuple>
  6. #include <vector>
  7.  
  8. using namespace std;
  9.  
  10. // Породы кошек
  11. enum class CatBreed {
  12.     Bengal,
  13.     Balinese,
  14.     Persian,
  15.     Siamese,
  16.     Siberian,
  17.     Sphynx,
  18. };
  19.  
  20. // Пол
  21. enum class Gender {
  22.     Male,
  23.     Female,
  24. };
  25.  
  26. struct Cat {
  27.     string name;
  28.     Gender gender;
  29.     CatBreed breed;
  30.     int age;
  31. };
  32.  
  33. string CatBreedToString(CatBreed breed) {
  34.     switch (breed) {
  35.     case CatBreed::Bengal:
  36.         return "Bengal"s;
  37.     case CatBreed::Balinese:
  38.         return "Balinese"s;
  39.     case CatBreed::Persian:
  40.         return "Persian"s;
  41.     case CatBreed::Siamese:
  42.         return "Siamese"s;
  43.     case CatBreed::Siberian:
  44.         return "Siberian";
  45.     case CatBreed::Sphynx:
  46.         return "Sphynx"s;
  47.     default:
  48.         throw invalid_argument("Invalid cat breed"s);
  49.     }
  50. }
  51.  
  52. ostream& operator<<(ostream& out, CatBreed breed) {
  53.     out << CatBreedToString(breed);
  54.     return out;
  55. }
  56.  
  57. ostream& operator<<(ostream& out, Gender gender) {
  58.     out << (gender == Gender::Male ? "male"s : "female"s);
  59.     return out;
  60. }
  61.  
  62. ostream& operator<<(ostream& out, const Cat& cat) {
  63.     out << '{' << cat.name << ", "s << cat.gender;
  64.     out << ", breed: "s << cat.breed << ", age:"s << cat.age << '}';
  65.     return out;
  66. }
  67.  
  68. // Возвращает массив указателей на элементы вектора cats, отсортированные с использованием
  69. // компаратора comp. Компаратор comp - функция, принимающая два аргумента типа const Cat&
  70. // и возвращающая true, если значения упорядочены, и false в ином случае
  71. template <typename Comparator>
  72. vector<const Cat*> GetSortedCats(const vector<Cat>& cats, const Comparator& comp) {
  73.     vector<const Cat*> sorted_cat_pointers;
  74.     for (const auto& cat : cats)
  75.     {
  76.         sorted_cat_pointers.push_back(&cat);
  77.     }
  78.  
  79.     sort(sorted_cat_pointers.begin(), sorted_cat_pointers.end(), [comp](const Cat* lhs, const Cat* rhs) {
  80.         return comp(*lhs, *rhs);
  81.     });
  82.    
  83.     /*
  84.     Напишите тело функции самостоятельно. Подсказка:
  85.     1) Поместите в массив sorted_cat_pointers адреса объектов из массива cats.
  86.     2) Отсортируйте массив sorted_cat_pointers с помощью переданного компаратора comp.
  87.        Так как comp сравнивает ссылки на объекты, а отсортировать нужно указатели,
  88.        передайте в sort лямбда функцию, принимающую указатели и сравнивающую объекты
  89.        при помощи компаратора comp:
  90.        [comp](const Cat* lhs, const Cat* rhs) {
  91.            return comp(*lhs, *rhs);
  92.        }
  93.     */
  94.     return sorted_cat_pointers;
  95. }
  96.  
  97. // Выводит в поток out значения объектов, на который ссылаются указатели вектора cat_pointers.
  98. // Пример вывода элементов vector<const Cat*>:
  99. // {{Tom, male, breed: Bengal, age:2}, {Charlie, male, breed: Balinese, age:7}}
  100. void PrintCatPointerValues(const vector<const Cat*>& cat_pointers, ostream& out) {
  101.     if (cat_pointers.empty())
  102.         out << "{}";
  103.     else {
  104.         out << "{";
  105.         bool alpha_ = true;
  106.         for (const auto& cat_pointer : cat_pointers)
  107.         {
  108.             if (alpha_)
  109.             {
  110.                 out << *cat_pointer;
  111.                 alpha_ = false;
  112.             }
  113.             else
  114.             {
  115.                 out << ", " << *cat_pointer;
  116.             }
  117.         }
  118.        
  119.        
  120.         out << "}";
  121.     }
  122. }
  123.        
  124.  
  125. int main() {
  126.     const vector<Cat> cats = {
  127.         {"Tom"s, Gender::Male, CatBreed::Bengal, 2},
  128.         {"Leo"s, Gender::Male, CatBreed::Siberian, 3},
  129.         {"Luna"s, Gender::Female, CatBreed::Siamese, 1},
  130.         {"Charlie"s, Gender::Male, CatBreed::Balinese, 7},
  131.         {"Ginger"s, Gender::Female, CatBreed::Sphynx, 5},
  132.         {"Tom"s, Gender::Male, CatBreed::Siamese, 2},
  133.     };
  134.  
  135.     {
  136.         auto sorted_cats = GetSortedCats(cats, [](const Cat& lhs, const Cat& rhs) {
  137.             return tie(lhs.breed, lhs.name) < tie(rhs.breed, rhs.name);
  138.             });
  139.  
  140.         cout << "Cats sorted by breed and name:"s << endl;
  141.         PrintCatPointerValues(sorted_cats, cout);
  142.         cout << endl;
  143.     }
  144.  
  145.     {
  146.         auto sorted_cats = GetSortedCats(cats, [](const Cat& lhs, const Cat& rhs) {
  147.             return tie(lhs.gender, lhs.breed) < tie(rhs.gender, rhs.breed);
  148.             });
  149.  
  150.         cout << "Cats sorted by gender and breed:"s << endl;
  151.         PrintCatPointerValues(sorted_cats, cout);
  152.         cout << endl;
  153.     }
  154.     return 0;
  155. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement