shushus

Спринт 2. Обобщаем функцию.

Dec 8th, 2022
209
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.28 KB | None | 0 0
  1. #include <iostream>
  2. #include <map>
  3. #include <string>
  4. #include <vector>
  5. #include <algorithm>
  6. using namespace std;
  7. template <typename Term>
  8. map<Term, int> ComputeTermFreqs(const vector<Term>& terms) {
  9.     map<Term, int> term_freqs;
  10.     for (const Term& term : terms) {
  11.         ++term_freqs[term];
  12.     }
  13.     return term_freqs;
  14. }
  15.  
  16. pair<string, int> FindMaxFreqAnimal(const vector<pair<string, int>>& animals) {
  17.     // верните животного с максимальной частотой
  18.     //sort(begin(animals), end(animals), [](const Term& lhs, const Term& rhs){return ComputeTermFreqs(lhs)})
  19.     /*vector<map<Term, int>> result;
  20.     for (const auto& animal : animals){
  21.         result.push_back(ComputeTermFreqs(animal));
  22.     }
  23.     sort(begin(result), end(result), [](const auto& lhs, const auto& rhs){
  24.                             if(lhs.second == rhs.second){
  25.                             return lhs.first.second < rhs.first.second;
  26.                             }
  27.                             return lhs.second > rhs.second;
  28.                            
  29.     });
  30.     return result.first;*/
  31.     int max_value = 0;
  32.     map<pair<string, int>, int> helper = ComputeTermFreqs(animals);
  33.     pair<string, int> itog;
  34.     /*sort(animals.begin(), animals.end(), [] (const auto& lhs, const auto& rhs){
  35.                                                 return lhs.first > rhs.first;});*/
  36.    
  37.     for (const auto& [animal, key] : helper){
  38.             if (key>max_value) {
  39.                 max_value=key;
  40.                 itog = animal;
  41.             }
  42.         }
  43. return itog;
  44. }
  45.    
  46.  
  47.  
  48.  
  49. /*vector{<Олень, 5>, 10>, <Енот, 2>, 6>, <Аллигатор, 3>, 10>}
  50. Аллигатор, 3 - 10
  51. Олень, 5 - 10
  52. Енот, 2 - 6*/
  53.  
  54.  
  55.  
  56. int main() {
  57.     const vector<pair<string, int>> animals = {
  58.         {"Murka"s, 5},  // 5-летняя Мурка
  59.         {"Belka"s, 6},  // 6-летняя Белка
  60.         {"Murka"s, 7},  // 7-летняя Мурка не та же, что 5-летняя!
  61.         {"Murka"s, 5},  // Снова 5-летняя Мурка
  62.         {"Belka"s, 6},  // Снова 6-летняя Белка
  63.     };
  64.     const pair<string, int> max_freq_animal = FindMaxFreqAnimal(animals);
  65.     cout << max_freq_animal.first << " "s << max_freq_animal.second << endl;
  66. }
Advertisement
Add Comment
Please, Sign In to add comment