O_Egor

database.h

Oct 15th, 2022 (edited)
725
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.66 KB | None | 0 0
  1. #pragma once
  2. #include "date.h"
  3. #include <map>
  4. #include <set>
  5. #include <vector>
  6. #include <memory>
  7. #include <algorithm>
  8.  
  9. using namespace std;
  10.  
  11. class Database
  12. {
  13. public:
  14.     void Add(const Date& _Date, const string& _Event);
  15.  
  16.     void Print(ostream& os) const;
  17.  
  18.     string Last(const Date& _Date) const;
  19.  
  20.     template <typename FuncName>
  21.     int RemoveIf(const FuncName& _Func);
  22.  
  23.     template <typename FuncName>
  24.     vector <pair <Date, string>> FindIf(const FuncName& _Func);
  25.  
  26. private:
  27.     map <Date, pair <set <string>, vector <set <string>::iterator>>> Records;
  28. };
  29.  
  30.  
  31. template <typename FuncName>
  32. int Database::RemoveIf(const FuncName& _Func)
  33. {
  34.     int counter = 0;
  35.  
  36.     for (auto& [key, value] : Records)
  37.     {
  38.         auto it = stable_partition(value.second.begin(), value.second.end(), [&_Func, &key, &value, &counter](const auto& _Event) -> bool
  39.         {
  40.             if (_Func(key, *_Event))
  41.             {
  42.                 ++counter;
  43.                 value.first.erase(*_Event);
  44.                 return false;
  45.             }
  46.             return true;
  47.         });
  48.         value.second.erase(it, value.second.end());
  49.     }
  50.  
  51.     for (auto eraseIt = Records.cbegin(), nextIt = eraseIt; eraseIt != Records.end(); eraseIt = nextIt)
  52.     {
  53.         ++nextIt;
  54.         if (eraseIt->second.first.empty())
  55.         {
  56.             Records.erase(eraseIt);
  57.         }
  58.  
  59.     }
  60.  
  61.     return counter;
  62. }
  63.  
  64. template <typename FuncName>
  65. vector <pair <Date, string>> Database::FindIf(const FuncName& _Func)
  66. {
  67.     vector <pair <Date, string>> ans;
  68.  
  69.     for (const auto& [_Key, _Value] : Records)
  70.     {
  71.         auto it = find_if(_Value.second.begin(), _Value.second.end(), [&_Key, &ans, &_Func](const auto& _Event)
  72.             {
  73.                 if (_Func(_Key, *_Event))
  74.                 {
  75.                     ans.push_back({ _Key, *_Event });
  76.                 }
  77.                 return false;
  78.             });
  79.     }
  80.  
  81.     return ans;
  82. }
Advertisement
Add Comment
Please, Sign In to add comment