Advertisement
RobertDeMilo

YB1.4 Упрощаем оператор сравнения

Oct 27th, 2023
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.05 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <tuple>
  4.  
  5. using namespace std;
  6.  
  7. struct Date
  8. {
  9.     int year;
  10.     //int month;
  11.     string month;
  12.     int day;
  13. };
  14.  
  15. // Мы должны хранить объекты в ключах словарей.
  16. // Поскольоку словарь хранит свои ключи отсортированными, нужно для этого типа определить оператор меньше
  17.  
  18. //bool operator <(const Date& lhs, const Date& rhs)
  19. //{
  20. //  // Если у дат разные года
  21. //  if (lhs.year != rhs.year)
  22. //  {
  23. //      return lhs.year < rhs.year;
  24. //  }
  25. //  // Если у дат одинаковые года, но разные месяцы
  26. //  if (lhs.month != rhs.month)
  27. //  {
  28. //      return lhs.month < rhs.month;
  29. //  }
  30. //  // Сравниваем дни, если все остальное одинаково
  31. //  return lhs.day < rhs.day;
  32. //}
  33.  
  34. //bool operator <(const Date& lhs, const Date& rhs)
  35. //{
  36. //  return vector<int>{lhs.year, lhs.month, lhs.day} <
  37. //      vector<int>{rhs.year, rhs.month, rhs.day};
  38. //  // Для векторов уже определен (лексикографический) оператор сравнения
  39. //}
  40.  
  41. bool operator <(const Date& lhs, const Date& rhs)
  42. {
  43.     // Создали кортеж, в котором все поля это ссылки.
  44.     // поэтому строки lhs.month и rhs.month не скопировались внутрь кортежей
  45.  
  46.     tuple<const int&, const string&, const int&> lhs_key = tie(lhs.year, lhs.month, lhs.day);
  47.     tuple<const int&, const string&, const int&> rhs_key = tie(rhs.year, rhs.month, rhs.day);
  48.  
  49.     return lhs_key < rhs_key;
  50.  
  51.     /*return tie(lhs.year, lhs.month, lhs.day) <
  52.         tie(rhs.year, rhs.month, rhs.day);*/
  53.         // Для векторов уже определен (лексикографический) оператор сравнения
  54. }
  55.  
  56. int main()
  57. {
  58.     cout << (Date{ 2017,"June",8 } < Date{ 2017,"January",26 }) << endl;
  59.  
  60.     return 0;
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement