-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path12.30.cpp
95 lines (80 loc) · 2.02 KB
/
12.30.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include<string>
#include<vector>
#include<map>
#include<set>
#include<fstream>
#include<sstream>
#include<iostream>
#include<memory>
using namespace std;
using line_no = std::vector<std::string>::size_type;
class QueryResult;
class TextQuery{
public:
using line_no = std::vector<std::string>::size_type;
TextQuery(std::ifstream&);
QueryResult query(const std::string&) const;
private:
std::shared_ptr<std::vector<std::string>> file;
std::map<std::string , std::shared_ptr<std::set<line_no>>> wm;
};
TextQuery::TextQuery(ifstream &is):file(new vector<string>)
{
string text;
while(getline(is,text)){
file -> push_back(text);
int n = file -> size() -1;
istringstream line(text);
string word;
while(line >> word){
auto &lines = wm[word];
if(!lines)
lines.reset(new set<line_no>);
lines -> insert(n);
}
}
};
class QueryResult{
friend std::ostream& print(std::ostream&, const QueryResult&);
public:
QueryResult(std::string s, std::shared_ptr<std::set<line_no>> p, std::shared_ptr<std::vector<std::string>> f):sought(s),lines(p),file(f){}
private:
std::string sought;
std::shared_ptr<std::set<line_no>> lines;
std::shared_ptr<std::vector<std::string>> file;
};
QueryResult TextQuery::query(const string &sought) const{
static shared_ptr<set<line_no>> nodata(new set<line_no>);
auto loc = wm.find(sought);
if(loc == wm.end())
return QueryResult(sought, nodata, file);
else
return QueryResult(sought,loc->second,file);
}
ostream& print(ostream& os, const QueryResult &qr)
{
os << qr.sought << " occurs " << qr.lines->size() << " times " << endl;
for(auto num : *qr.lines){
os << "\t(line " << num + 1 << ")" << *(qr.file->begin() + num) << endl;
}
return os;
}
void runQueries(ifstream& infile)
{
TextQuery tq(infile);
while(true){
cout << "enter word to look for, or q to quit: ";
string s;
if(!(cin >> s) || s == "q" ) break;
print(cout, tq.query(s)) << endl;
}
}
int main(int argc, char* argv[])
{
ifstream in(argv[1]);
if(in){
runQueries(in);
}
system("pause");
return 0;
}