forked from jaege/Cpp-Primer-5th-Exercises
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TextQuery.cpp
34 lines (32 loc) · 1009 Bytes
/
TextQuery.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
#include <sstream>
#include "TextQuery.h"
#include "QueryResult.h"
#include "StrBlob.h"
#include "StrBlobPtr.h"
TextQuery::TextQuery(std::ifstream &in)
: text(new StrBlob), word_map() {
for (std::string line; std::getline(in, line); text->push_back(line)) {
std::istringstream iss(line);
for (std::string word; iss >> word; ) {
auto &lns = word_map[word];
if (!lns)
lns.reset(new std::set<line_no_type>);
lns->insert(text->size());
}
}
}
QueryResult TextQuery::query(const std::string &word) const {
static std::shared_ptr<std::set<line_no_type>>
nodata(new std::set<line_no_type>);
auto it = word_map.find(word);
if (it == word_map.end())
return QueryResult(word, 0, nodata, text);
line_no_type total = 0;
for (const auto &ln : *(it->second)) {
std::istringstream iss(StrBlobPtr(*text, ln).deref());
for (std::string wd; iss >> wd; )
if (wd == word)
++total;
}
return QueryResult(word, total, it->second, text);
}