-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
ex12_32.cpp
54 lines (50 loc) · 1.71 KB
/
ex12_32.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
//
// ex12_32.cpp
// Exercise 12.32
//
// Created by pezy on 1/1/15.
// Copyright (c) 2015 pezy. All rights reserved.
//
// Rewrite the TextQuery and QueryResult classes to use a StrBlob
// instead of a vector<string> to hold the input file.
#include "ex12_32.h"
#include <sstream>
#include <algorithm>
TextQuery::TextQuery(std::ifstream& ifs) : input(new StrBlob)
{
StrBlob::size_type lineNo{0};
for (string line; std::getline(ifs, line); ++lineNo) {
input->push_back(line);
std::istringstream line_stream(line);
for (string text, word; line_stream >> text; word.clear()) {
// avoid read a word followed by punctuation(such as: word, )
std::remove_copy_if(text.begin(), text.end(),
std::back_inserter(word), ispunct);
// use reference avoid count of shared_ptr add.
auto& nos = result[word];
if (!nos) nos.reset(new std::set<StrBlob::size_type>);
nos->insert(lineNo);
}
}
}
QueryResult TextQuery::query(const string& str) const
{
// use static just allocate once.
static shared_ptr<std::set<StrBlob::size_type>> nodate(
new std::set<StrBlob::size_type>);
auto found = result.find(str);
if (found == result.end())
return QueryResult(str, nodate, input);
else
return QueryResult(str, found->second, input);
}
std::ostream& print(std::ostream& out, const QueryResult& qr)
{
out << qr.word << " occurs " << qr.nos->size()
<< (qr.nos->size() > 1 ? " times" : " time") << std::endl;
for (auto i : *qr.nos) {
ConstStrBlobPtr p(*qr.input, i);
out << "\t(line " << i + 1 << ") " << p.deref() << std::endl;
}
return out;
}