Advertisement
Guest User

inverted_index.cpp

a guest
May 26th, 2016
1,058
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.38 KB | None | 0 0
  1. #include <iostream>
  2. #include <iterator>
  3. #include <fstream>
  4. #include <map>
  5. #include <vector>
  6. #include <string>
  7.  
  8. using index_type = std::map<std::string, std::vector<std::string>>;
  9.  
  10. bool AppendToIndex(index_type& index, std::string filename) {
  11.     std::ifstream file(filename);
  12.  
  13.     if (!file.is_open())
  14.         return false;
  15.  
  16.     while (!file.eof()) {
  17.         std::string word;
  18.         file >> word;
  19.  
  20.         auto inserted = index.insert({word, {filename}});
  21.  
  22.         if (!inserted.second)
  23.             inserted.first->second.push_back(filename);
  24.     }
  25.  
  26.     return true;
  27. }
  28.  
  29. int main() {
  30.     index_type index{};
  31.  
  32.     for (auto s : {"file1.txt", "file2.txt", "file3.txt"}) {
  33.         if (!AppendToIndex(index, s))
  34.             std::cout << "Warning: could not open " << s << "!\n";
  35.     }
  36.  
  37.     std::string line;
  38.  
  39.     while (true) {
  40.         std::cout << "Enter a word to search or hit return to exit: ";
  41.  
  42.         if (!std::getline(std::cin, line) || line.empty())
  43.             break;
  44.  
  45.         auto pos = index.find(line);
  46.  
  47.         if (pos == index.end())
  48.             std::cout << "Word was found in none of the files!\n";
  49.         else {
  50.             std::cout << "Word was found in: {";
  51.             std::copy(pos->second.begin(), pos->second.end(),
  52.                 std::ostream_iterator<std::string>(std::cout, ", "));
  53.             std::cout << "\b\b}\n";
  54.         }
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement