-
-
Save JeOam/66b5d4f0c493f7bd7385429f17dcfc9f to your computer and use it in GitHub Desktop.
C++ 文本查询程序设计(12.3.1)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Author
JeOam
commented
Jul 14, 2018
•
class QueryResult;
class TextQuery {
public:
using line_no = std::vector<std::string>::size_type;
TextQuery(std::ifstream&);
QueryResult query(const std::string&) const;
private:
std::shared_ptr<std::vector<std::string>> file;
std::map<std::string, std::shared_ptr<std::set<line_no>>> wm;
};
TextQuery::TextQuery(ifsteam &is): file(new vector<string>)
{
string text;
while (getline(is, text)) {
file->push_back(text);
int n = file->size() - 1;
istringstream line(text);
string word;
while (line >> word) {
auto &lines = wm[word];
if (!lines) {
lines.reset(new set(line_no);
}
lines->insert(n);
}
}
};
class QueryResult {
friend std::ostream& print(std:ostream&, const QueryResult&);
public:
QueryResult(std::string s,
std::shared_ptr<std::set<line_no>> p,
std::shared_ptr<std::vector<std::string>> f
): sought(s), lines(p), file(f) {}
private:
std::string sought;
std::shared_ptr<std::set<line_no>> lines;
std::shared_ptr<std::vector<std::string>> file;
}
QueryResult TextQuery::query(const string &sought) const
{
static shared_ptr<set<line_no>> nodata(new set<line_no>);
auto loc = wm.find(sought);
if (loc == wm.end())
return QueryResult(sought, nodata, file)
else
return QueryResult(sought, loc->second, file);
}
ostream &print(ostream & os, cosnt QueryResult &qr)
{
os << qr.sought << " occurs " << qr.lines->size() << " "
<< make_plural(qr.lines->size(), "time", "s") << endl;
for (auto num: *qr.lines)
os << "\t(line )" << num + 1 << ") "
<< *(qr.file->begin() + num) << endl;
return os;
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment