// 文本查詢程序.cpp : 定義控制臺應用程序的入口點断箫。
//
#include "stdafx.h"
#include<iostream>
#include<fstream>
#include<vector>
#include<map>
#include<set>
#include<string>
#include<sstream>
#include<memory>
#include<new>
using namespace std;
using line_no = vector<string>::size_type;
class QueryResult//儲存查詢結果并輸出拂酣!
{
public:
QueryResult(string s, shared_ptr<set<line_no>> p, shared_ptr<vector<string>> f) :find_word(s), lines(p), file(f) {}
friend ostream &print(ostream &os, const QueryResult &qr);
private:
string find_word;
shared_ptr<set<line_no>> lines;
shared_ptr<vector<string>> file;
};
class TextQuery//讀取文件,并返回查詢結果至存儲類仲义!
{
public:
TextQuery() = default;
TextQuery(istream &in){ read(in); }
void read_from_file(istream &in) { read(in); }
QueryResult query(const string &find_word) const; //創(chuàng)建queryresult對象婶熬!
private:
void read(istream &in);
shared_ptr<vector<string>> file=make_shared<vector<string>>(); // 如果創(chuàng)建空的只能指針,必須進行綁定(初始化)才可以使用埃撵!為什么不能使用new赵颅?
map<string, shared_ptr<set<line_no>>> wm; //共享數(shù)據(jù),避免拷貝增加計算量暂刘!
};
void TextQuery::read(istream &in)
{
string text;
while (getline(in, text))
{
file->push_back(text);
int n = file->size() - 1;
istringstream line(text);
string word;
while (line >> word)
{
auto &lines = wm[word];
if (!lines)//如果對應word鍵值不存在饺谬,則創(chuàng)建對象,同時鍵值為空谣拣。通過智能指針reset操作募寨,重新指向new set<line_no>
lines.reset(new set<line_no>);
lines->insert(n);
}
}
}
QueryResult TextQuery::query(const string &find_word) const
{
static shared_ptr<set<line_no>> nodata(new set<line_no>); //靜態(tài)智能指針,避免函數(shù)調(diào)用結束后森缠,局部變量釋放了拔鹰!由于只創(chuàng)建了空指針,在讀取字符串時可能存在沒有綁定內(nèi)存空間贵涵!因此創(chuàng)建初始化靜態(tài)指針表示未找到單詞A兄(shared_ptr引用則計數(shù)加1,計數(shù)沒減到0宾茂,則不會釋放呀瓷马?)
auto loc = wm.find(find_word);/
/返回指向數(shù)據(jù)的迭代器!
if (loc == wm.end())
return QueryResult(find_word, nodata, file);
else
return QueryResult(find_word, loc->second, file);
}
void runQueries(ifstream &infile)
{
TextQuery tq(infile);
while (true)
{
string s;
cout << "Enter a word to look for,or q to quit:";
if (!(cin >> s) || s == "q")
break;
print(cout, tq.query(s)) << endl;
}
}
ostream &print(ostream &os, const QueryResult &qr)
{
os << qr.find_word<<" occurs "<<qr.lines->size()<<" times"<<endl;
for (auto &num : *(qr.lines))
{
os << "\t(line " << num + 1 << ") " << *(qr.file->begin() + num) << endl;
}
return os;
}
int main()
{
ifstream file("C:/Users/winack/Documents/Visual Studio 2017/Projects/文本查詢程序/123.txt");
TextQuery t_1;
t_1.read_from_file(file);
QueryResult result_you=t_1.query("you");
print(cout, result_you) << endl;
file.close();
system("pause");
return 0;
}
//面向對象的核心是刻炒,抽象繼承多態(tài)决采。
抽象把數(shù)據(jù)實現(xiàn)隱藏,暴露公共接口
繼承和多態(tài)坟奥,派生類繼承基類树瞭,降低代碼重復性,通過指針引用調(diào)用派生類爱谁,實現(xiàn)多態(tài)晒喷!