练习12.27:
class QueryResult;
class TextQuery
{
public:
//构造函数
TextQuery(ifstream& infile);
//定义查询结果函数query
QueryResult query(const string& s)const;
private:
std::shared_ptr<std::vector<std::string>>file;
std::_In_place_key_extract_map<std::string, shared_ptr<std::set<std::vector<std::string>::size_type>>>wm;
};
class QueryResult
{
public:
//构造函数
QueryResult(std::string s,std::shared_ptr<std::set<std::vector<std::string>::size_type>>p,
std::shared_ptr<std::vector<std::string>>f) : sought(s),lines(p),file(f){ }
private:
//查询的单词
std::string sought;
//出现的行号
std::shared_ptr<std::set<std::vector<string>::size_type>>lines;
//输入的文件
std::shared_ptr<std::vector<std::string>>file;
};
练习12.28:
#include <iostream>
#include <string>
using namespace std;
#include <vector>
#include <fstream>
#include <memory>
#include <set>
#include <map>
#include <sstream>
//读取文件
void ReadFile(ifstream& infile, vector<string>& file, map<string, set<vector<string>::size_type>>& mp)
{
string line;
while (getline(infile, line))
{
file.push_back(line);
//记录行号,从第0行开始
int num = file.size() - 1;
istringstream istr(line);
string word;
while (istr >> word)
{
mp[word].insert(num);
}
}
}
//查询打印
ostream& findWord(ostream& os, const string& sought,map<string,set<vector<string>::size_type>>& mp,vector<string>& file)
{
//在map中查找单词
auto it = mp.find(sought);
if (it == mp.end())
{
os << sought << " occurs 0 time" << endl;
}
else
{
//打印行号及出现的行
set<vector<string>::size_type> num = it->second;
os << sought << " occurs " << num.size() << " times" << endl;
//按升序打印出现的行
for (const auto& c : num)
{
os << "(line " << c << " )" << file[c] << endl;
}
}
return os;
}
//用户查询单词
void QueryWord(ifstream& infile, map<string, set<vector<string>::size_type>>& mp, vector<string>& file)
{
ReadFile(infile, file, mp);
while (true)
{
cout << "enter word to look for,or q to quit: ";
string s;
if (!(cin >> s) || s == "q")
{
break;
}
//查询结果并打印
findWord(cout, s, mp, file) << endl;
}
}
int main()
{
//保存文本
vector<string>file;
//保存映射
map<string, set<vector<string>::size_type>>mp;
ifstream infile("text.txt");
QueryWord(infile, mp, file);
system("pause");
return 0;
}
结果:
文件内容:
练习12.29:使用do while重写程序,同样可以很好的实现,但是之前的写法更好,简单易懂
//用户查询单词
void QueryWord(ifstream& infile, map<string, set<vector<string>::size_type>>& mp, vector<string>& file)
{
ReadFile(infile, file, mp);
do
{
cout << "enter word to look for,or q to quit: ";
string s;
if (!(cin >> s) || s == "q")
{
break;
}
//查询结果并打印
findWord(cout, s, mp, file) << endl;
} while (true);
}