QueryResult.h
#pragma once
#include<memory>
#include<set>
#include<string>
#include<vector>
class QueryResult {
using line_no = std::vector<std::string>::size_type;
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){}
friend std::ostream &print(std::ostream& os, const QueryResult&qr);
private:
std::string sought;
std::shared_ptr<std::set<line_no> > lines;
std::shared_ptr<std::vector<std::string> > file;
};
TextQuery.h
#pragma once
#include<fstream>
#include<string>
#include<sstream>
#include<vector>
#include<memory>
#include<map>
#include<set>
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.cpp
#include"TextQuery.h"
#include"QueryResult.h"
TextQuery::TextQuery(std::ifstream& infile) :file(new std::vector<std::string>)
{
std::string line;
while (getline(infile, line)) {
file->push_back(line);
int n = file->size();
std::istringstream aline(line);
std::string word;
while (aline >> word) {
auto &lines = wm[word];
if (!lines)
lines.reset(new std::set<line_no>);
lines->insert(n);
}
}
}
QueryResult TextQuery::query(const std::string&sought) const {
static std::shared_ptr<std::set<line_no>> nodate(new std::set<line_no>);
auto loc = wm.find(sought);
if (loc == wm.end()) {
return QueryResult(sought, nodate, file);
}
else
{
return QueryResult(sought, loc->second, file);
}
}
Main
#include"TextQuery.h"
#include"QueryResult.h"
#include<iostream>
std::ostream &print(std::ostream& os, const QueryResult&qr) {
os << qr.sought << " occurs " << qr.lines->size() << (qr.lines->size() > 1 ? " times" : " time") << std::endl;
for (auto num : *qr.lines) {
os << "\t(line " << num << ") "<< *(qr.file->begin() + num - 1) << std::endl;
}
return os;
}
void runQueries(std::ifstream &infile) {
TextQuery tq(infile);
while (true) {
std::cout << "enter word to look for,or q to quit: ";
std::string s;
if (!(std::cin >> s) || s == "q")
break;
print(std::cout, tq.query(s)) << std::endl;
}
}
int main(){
runQueries(std::ifstream("TXT.txt"));
return 0;
}