|
| 1 | +#include <iostream> |
| 2 | +#include <vector> |
| 3 | +#include <string> |
| 4 | +#include <fstream> |
| 5 | +#include <memory> |
| 6 | +#include <map> |
| 7 | +#include <set> |
| 8 | +#include <sstream> |
| 9 | +class TextQuery { |
| 10 | + public: |
| 11 | + class QueryResult; |
| 12 | + using line_no = std::vector<std::string>::size_type; |
| 13 | + TextQuery(std::ifstream&); |
| 14 | + TextQuery::QueryResult query(const std::string&) const; |
| 15 | + private: |
| 16 | + std::shared_ptr<std::vector<std::string> > file; |
| 17 | + std::map<std::string, std::shared_ptr<std::set<line_no> > > wm; |
| 18 | +}; |
| 19 | + |
| 20 | +class TextQuery::QueryResult{ |
| 21 | + friend std::ostream& print(std::ostream&, const QueryResult&); |
| 22 | + public: |
| 23 | + QueryResult(std::string s, std::shared_ptr<std::set<line_no> > p, |
| 24 | + std::shared_ptr<std::vector<std::string> > f):sought(s),lines(p),file(f){}; |
| 25 | + private: |
| 26 | + std::string sought; //query word |
| 27 | + std::shared_ptr<std::set<line_no> > lines; //lines the word show |
| 28 | + std::shared_ptr<std::vector<std::string> > file; //files show the word; |
| 29 | +}; |
| 30 | + |
| 31 | +TextQuery::TextQuery(std::ifstream &is) : file(new std::vector<std::string> ){ |
| 32 | + std::string text; |
| 33 | + while (getline(is, text)) { |
| 34 | + file->push_back(text); |
| 35 | + int n = file->size() - 1; |
| 36 | + std::istringstream line(text); |
| 37 | + std::string word; |
| 38 | + while (line >> word) { |
| 39 | + auto &lines = wm[word]; |
| 40 | + if (!lines) { |
| 41 | + lines.reset(new std::set<line_no>); |
| 42 | + } |
| 43 | + lines->insert(n); |
| 44 | + } |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +TextQuery::QueryResult |
| 49 | +TextQuery::query(const std::string &sought) const{ |
| 50 | + static std::shared_ptr<std::set<line_no> > nodata(new std::set<line_no>); |
| 51 | + auto loc = wm.find(sought); |
| 52 | + if (loc == wm.end()) { |
| 53 | + return TextQuery::QueryResult(sought, nodata, file); |
| 54 | + } |
| 55 | + else { |
| 56 | + return TextQuery::QueryResult(sought,loc->second,file); |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +std::ostream &print (std::ostream & os, const TextQuery::QueryResult & qr) |
| 61 | +{ |
| 62 | + os << qr.sought << " occurls " << qr.lines->size() << " time(s)" << std::endl; |
| 63 | + for (auto i : *qr.lines) { |
| 64 | + os << "\t(line " << i+1 << ") " << *(qr.file->begin() + i) << std::endl; |
| 65 | + } |
| 66 | + return os; |
| 67 | +} |
| 68 | + |
| 69 | +int main(int argc, char *argv[]) |
| 70 | +{ |
| 71 | + std::ifstream file; |
| 72 | + file.open("ex19_18.cpp"); |
| 73 | + TextQuery si(file); |
| 74 | + auto res = si.query("std"); |
| 75 | + print(std::cout, res); |
| 76 | + return 0; |
| 77 | +} |
0 commit comments