forked from Mooophy/Cpp-Primer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
textquery.cpp
75 lines (66 loc) · 2.25 KB
/
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
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
/***************************************************************************
* @file textqueryr.cpp
* @author Alan.W
* @date 29 DEC 2013
* @remark
***************************************************************************/
#include "textquery.h"
#include "queryresult.h"
#include <iterator>
#include <algorithm>
#include <sstream>
// Constructor
TextQuery::TextQuery(std::ifstream & is) : file(new std::vector<std::string>)
{
// each line
std::string line;
while(std::getline(is, line))
{
file->push_back(line);
// current line index
int index = file->size() - 1;
// for each word
std::stringstream lineSteam(line);
std::string word;
while(lineSteam >> word)
{
// fetch the smart pointer which is null when the word first time seen
std::shared_ptr<std::set<index_Tp>>& sp_lineIndex = wm[word];
// if null, allcate a new set to contain line indices
if(!sp_lineIndex)
sp_lineIndex.reset(new std::set<index_Tp>);
// insert
sp_lineIndex->insert(index);
}
}
}
/**
* @brief do a query opertion and return QueryResult object.
*/
QueryResult
TextQuery::query(const std::string &sought) const
{
// dynamicaly allocated set used for the word does not appear.
static std::shared_ptr<std::set<index_Tp>> noData(new std::set<index_Tp>);
// fetch the iterator to the matching element in the map<word, lines>.
//std::map<std::string, std::shared_ptr<std::set<index_Tp>>>::const_iterator
auto iter = wm.find(sought);
if(iter == wm.end())
return QueryResult(sought, noData, file);
else
return QueryResult(sought, iter->second, file);
}
/**
* @brief do a query opertion and return tuple.
*/
result_tuple TextQuery::query_return_tuple(const std::string &sought)
{
// dynamicaly allocated set used for the word does not appear.
static std::shared_ptr<std::set<index_Tp>> noData(new std::set<index_Tp>);
// fetch the iterator to the matching element in the map<word, lines>.
auto iter = wm.find(sought);
if(iter == wm.end())
return result_tuple(sought, noData, file);
else
return result_tuple(sought, iter->second, file);
}