fork(8) download
  1. #include <vector>
  2. #include <map>
  3. #include <set>
  4. #include <iostream>
  5. #include <string>
  6. #include <cstdint>
  7.  
  8. typedef std::string IDdoc;
  9. typedef uint32_t position;
  10.  
  11. typedef std::pair<IDdoc,position> Occurrence;
  12. typedef std::vector<Occurrence> OccurrencesOfWord;
  13. typedef std::map<std::string /*word*/, OccurrencesOfWord> Dictionary;
  14. typedef std::set<IDdoc> Matches;
  15.  
  16. bool findMatchesForPhrase(const std::string& phrase, const Dictionary& dictionary, Matches& matches)
  17. {
  18. size_t pos = 0;
  19. size_t len = 0;
  20. while (pos < phrase.length()) {
  21. size_t end = phrase.find(' ', pos);
  22. size_t len = ((end == phrase.npos) ? phrase.length() : end) - pos;
  23. std::string word(phrase, pos, len);
  24. pos += len + 1; // to skip the space.
  25.  
  26. // ignore words not in the dictionary.
  27. auto dictIt = dictionary.find(word);
  28. if (dictIt == dictionary.end())
  29. continue;
  30.  
  31. auto& occurrences = dictIt->second; // shortcut/alias,.
  32. for (auto& occurIt : occurrences) {
  33. // Add all the IDdoc's of this occurence to the set.
  34. matches.insert(occurIt.first);
  35. }
  36. }
  37.  
  38. return !matches.empty();
  39. }
  40.  
  41. void addToDictionary(Dictionary& dict, const char* word, const char* doc, uint32_t position)
  42. {
  43. dict[word].push_back(std::make_pair(std::string(doc), position));
  44. }
  45.  
  46. int main(int argc, const char** argv)
  47. {
  48. std::string phrase("pizza is life");
  49. Dictionary dict;
  50.  
  51. addToDictionary(dict, "pizza", "book1", 10);
  52. addToDictionary(dict, "pizza", "book2", 30);
  53. addToDictionary(dict, "life", "book1", 1);
  54. addToDictionary(dict, "life", "book3", 1);
  55. addToDictionary(dict, "goat", "book4", 99);
  56.  
  57. Matches matches;
  58. bool result = findMatchesForPhrase(phrase, dict, matches);
  59.  
  60. std::cout << "result = " << result << std::endl;
  61. for (auto& ent : matches) {
  62. std::cout << ent << std::endl;
  63. }
  64.  
  65. return 0;
  66. }
Success #stdin #stdout 0s 2992KB
stdin
Standard input is empty
stdout
result = 1
book1
book2
book3