-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathTextQuery.cc
More file actions
55 lines (51 loc) · 1.42 KB
/
TextQuery.cc
File metadata and controls
55 lines (51 loc) · 1.42 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
46
47
48
49
50
51
52
53
54
55
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <memory>
#include <set>
#include <map>
#include <vector>
#include "TextQuery.h"
TextQuery::TextQuery(std::ifstream &in) : file(new std::vector<std::string>)
{
std::string text;
while (getline(in, text)) {
file->push_back(text);
int n = file->size() - 1;
std::istringstream line(text);
std::string word;
while (line >> word) {
auto &lines = wm[word];
if (!lines) {
lines.reset(new std::set<line_no>);
}
lines->insert(n);
}
}
}
TextQuery::QueryResult
TextQuery::query(const std::string &word) const
{
static std::shared_ptr<std::set<line_no>> nodata(new std::set<line_no>{});
auto loc = wm.find(word);
if (loc == wm.end()) {
return QueryResult(word, nodata, file);
} else
return QueryResult(word, loc->second, file);
}
std::string
make_plural(size_t ctr, const std::string &word, const std::string &ending)
{
return (ctr<=1)?word:word+ending;
}
std::ostream& print(std::ostream &os, const TextQuery::QueryResult &qr)
{
os << qr.sought << " occurs " << qr.lines->size() << " "
<< make_plural(qr.lines->size(), "time", "s") << std::endl;
for (auto num : *qr.lines) {
os << "\t(line " << num + 1 << ") "
<< *(qr.file->begin() + num) << std::endl;
}
return os;
}