Advertisement
kutuzzzov

Урок 4. Как устроены шаблоны

Nov 16th, 2021 (edited)
585
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.52 KB | None | 0 0
  1. #include <vector>
  2. #include <iostream>
  3. #include <string>
  4. #include <cmath>
  5. #include <map>
  6. #include <algorithm>
  7. using namespace std;
  8.  
  9. template <typename Documents,typename Term>
  10. vector<double> ComputeTfIdfs(const Documents& documents, const Term& query){
  11.  
  12.     vector<double> result; // 1. создаю массив
  13.     int temp = 0;
  14.     double tf;
  15.     double idf;
  16.    
  17.     for (const auto& document : documents) { // 2. прохожу циклом, считаю ТФ и document_freq
  18.         int document_freq = count(document.begin(), document.end(), query);
  19.         if (document_freq != 0) {
  20.             tf = static_cast<double>(document_freq) / static_cast<double>(document.size());
  21.             result.push_back(tf);
  22.             ++temp;
  23.         } else {
  24.         result.push_back(0);
  25.         }
  26.     }
  27.     idf = log(static_cast<double>(documents.size()) / static_cast<double>(temp)); // 3. считаю ИДФ
  28.    
  29.     for (double& tf : result) { // 4. обновляю массив
  30.     tf *= idf;
  31.     }
  32.    
  33.     return result;
  34.  }
  35.  
  36. int main() {
  37.     const vector<vector<string>> documents = {
  38.         {"белый"s, "кот"s, "и"s, "модный"s, "ошейник"s},
  39.         {"пушистый"s, "кот"s, "пушистый"s, "хвост"s},
  40.         {"ухоженный"s, "пёс"s, "выразительные"s, "глаза"s},
  41.     };
  42.     const auto& tf_idfs = ComputeTfIdfs(documents, "кот"s);
  43.     for (const double tf_idf : tf_idfs) {
  44.         cout << tf_idf << " "s;
  45.     }
  46.     cout << endl;
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement