forked from chihyang/CPP_Primer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExer19_20_TextQuery.cpp
More file actions
45 lines (45 loc) · 1.96 KB
/
Copy pathExer19_20_TextQuery.cpp
File metadata and controls
45 lines (45 loc) · 1.96 KB
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
#include "Exer19_20_TextQuery.h"
// read the input file and build the std::map of lines to line numbers
TextQuery::TextQuery(std::ifstream& is) : file(new std::vector<std::string>)
{
std::string text;
while(getline(is, text)) //for each line in the file
{
file->push_back(text); // remember this line of text
int n = file->size() - 1; // the current line number
std::istringstream line(text); // separate the line into words
std::string word;
while(line >> word) // for each word in that line
{
// if word isn't already in wm, subscripting adds a new entry
auto &lines = wm[word]; // lines is a std::shared_ptr
if(!lines) // that pointer is null the first time we see word
lines.reset(new std::set<line_no>); // allocate a new std::set
lines->insert(n); // insert this line number
}
}
}
// return type must indicate that QueryResult is now a nested class
TextQuery::QueryResult TextQuery::query(const std::string& sought) const
{
// we'll return a pointer to this std::set if we don't find sought
static std::shared_ptr<std::set<line_no>> nodata(new std::set<line_no>);
//use find and not a subscript to avoid adding words to wm!
auto loc = wm.find(sought);
if(loc == wm.end())
return QueryResult(sought, nodata, file); // not found
else
return QueryResult(sought, loc->second, file);
}
// must indicate that QueryResult is a nested class
std::ostream& print(std::ostream& os, const TextQuery::QueryResult& qr)
{
// if the word was found, print the count and all occurrences
os << qr.sought << " occurs " << qr.lines->size() << " "
<< make_plural(qr.lines->size(), "time", "s") << std::endl;
// print each line in which the word appeared
for(auto num : *qr.lines)
os << "\t(line " << num + 1 << ") "
<<*(qr.file->begin() + num) << std::endl;
return os;
}