Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "search_server.h"
- #include "iterator_range.h"
- #include <algorithm>
- #include <iterator>
- #include <sstream>
- #include <iostream>
- #define sz(v) (int)v.size()
- vector<string> SplitIntoWords(const string& line) {
- istringstream words_input(line);
- return {istream_iterator<string>(words_input), istream_iterator<string>()};
- }
- SearchServer::SearchServer(istream& document_input) {
- UpdateDocumentBase(document_input);
- }
- void SearchServer::UpdateDocumentBase(istream& document_input) {
- InvertedIndex new_index;
- for (string current_document; getline(document_input, current_document); ) {
- new_index.Add(move(current_document));
- }
- index = move(new_index);
- }
- void SearchServer::AddQueriesStream(
- istream& query_input, ostream& search_results_output
- ) {
- vector<int> cnt (index.get_sz ());
- for (string current_query; getline(query_input, current_query); ) {
- const auto words = SplitIntoWords(current_query);
- for (auto& x: cnt) x = 0;
- for (const auto& word : words) {
- for (const int docid : index.Lookup(word)) {
- ++cnt[docid];
- }
- }
- set <pair <int, int>> kek;
- for (int i = 0; i < sz (cnt); ++i) {
- if (!cnt[i]) continue;
- if (sz (kek) < 5) kek.insert ({cnt[i], -i});
- else {
- auto it = kek.begin ();
- if (*it < make_pair (cnt[i], -i)) {
- kek.erase (it);
- kek.insert ({cnt[i], -i});
- }
- }
- }
- vector<pair<int, int>> res (kek.begin (), kek.end ());
- reverse (res.begin (), res.end ());
- search_results_output << current_query << ':';
- for (auto [hitcount, docid] : res) {
- search_results_output << " {"
- << "docid: " << -docid << ", "
- << "hitcount: " << hitcount << '}';
- }
- search_results_output << endl;
- }
- }
- void InvertedIndex::Add(const string& document) {
- docs.push_back(document);
- const size_t docid = docs.size() - 1;
- for (const auto& word : SplitIntoWords(document)) {
- index[word].push_back(docid);
- }
- }
- const vector<int>& InvertedIndex::Lookup(const string& word) const {
- if (auto it = index.find(word); it != index.end()) {
- return it->second;
- } else {
- return empty_vector;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement