Advertisement
Galebickosikasa

Untitled

Apr 2nd, 2021
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.24 KB | None | 0 0
  1. #include "search_server.h"
  2. #include "iterator_range.h"
  3.  
  4. #include <algorithm>
  5. #include <iterator>
  6. #include <sstream>
  7. #include <iostream>
  8.  
  9. #define sz(v) (int)v.size()
  10.  
  11. vector<string> SplitIntoWords(const string& line) {
  12. istringstream words_input(line);
  13. return {istream_iterator<string>(words_input), istream_iterator<string>()};
  14. }
  15.  
  16. SearchServer::SearchServer(istream& document_input) {
  17. UpdateDocumentBase(document_input);
  18. }
  19.  
  20. void SearchServer::UpdateDocumentBase(istream& document_input) {
  21. InvertedIndex new_index;
  22.  
  23. for (string current_document; getline(document_input, current_document); ) {
  24. new_index.Add(move(current_document));
  25. }
  26.  
  27. index = move(new_index);
  28. }
  29.  
  30. void SearchServer::AddQueriesStream(
  31. istream& query_input, ostream& search_results_output
  32. ) {
  33. vector<int> cnt (index.get_sz ());
  34. for (string current_query; getline(query_input, current_query); ) {
  35. const auto words = SplitIntoWords(current_query);
  36. for (auto& x: cnt) x = 0;
  37. for (const auto& word : words) {
  38. for (const int docid : index.Lookup(word)) {
  39. ++cnt[docid];
  40. }
  41. }
  42. set <pair <int, int>> kek;
  43. for (int i = 0; i < sz (cnt); ++i) {
  44. if (!cnt[i]) continue;
  45. if (sz (kek) < 5) kek.insert ({cnt[i], -i});
  46. else {
  47. auto it = kek.begin ();
  48. if (*it < make_pair (cnt[i], -i)) {
  49. kek.erase (it);
  50. kek.insert ({cnt[i], -i});
  51. }
  52. }
  53. }
  54. vector<pair<int, int>> res (kek.begin (), kek.end ());
  55. reverse (res.begin (), res.end ());
  56. search_results_output << current_query << ':';
  57. for (auto [hitcount, docid] : res) {
  58. search_results_output << " {"
  59. << "docid: " << -docid << ", "
  60. << "hitcount: " << hitcount << '}';
  61. }
  62. search_results_output << endl;
  63. }
  64. }
  65.  
  66. void InvertedIndex::Add(const string& document) {
  67. docs.push_back(document);
  68.  
  69. const size_t docid = docs.size() - 1;
  70. for (const auto& word : SplitIntoWords(document)) {
  71. index[word].push_back(docid);
  72. }
  73. }
  74.  
  75. const vector<int>& InvertedIndex::Lookup(const string& word) const {
  76. if (auto it = index.find(word); it != index.end()) {
  77. return it->second;
  78. } else {
  79. return empty_vector;
  80. }
  81. }
  82.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement