1 class QueryResult
2 {
3 public:
4 int frequence;
5 int hanghao[20];
6 string text[20];
7
8 QueryResult() :frequence(0), hanghao(), text() {};
9 QueryResult(int frequence, int h[], string t[]) :frequence(frequence)
10 {
11 for (int i = 0; i < 20; i++)
12 {
13 hanghao[i] = h[i];
14 text[i] = t[i];
15 }
16 };
17 /*void print(ostream &c, queryresult q);*/
18 friend class TextQuery;
19 };
20
21 class TextQuery
22 {
23 public:
24 TextQuery(ifstream& infile);
25 QueryResult query(string s);
26 private:
27 shared_ptr<vector<string>> data;
28 shared_ptr<map<string, set<int>>> mp;
29 };
30
31
32 TextQuery::TextQuery(ifstream& infile)
33 {
34 string text;
35 int hanghao = 1;
36 vector<string> d;
37 map<string, set<int>> m;
38 while (getline(infile, text))
39 {
40 istringstream stream(text);
41 string word;
42 d.push_back(text);
43 while (stream >> word)
44 {
45 int num = 0;
46 for (int i = 0; i < word.size(); i++)
47 {
48 string str(1,word[i]);
49 if (m.find(str) == m.end())
50 {
51 //第一次出现该单词
52 set<int> st;
53 st.insert(hanghao);
54 m[str] = st;
55 }
56 else
57 {
58 //已经出现该单词
59 auto q = m.find(str);
60 q->second.insert(hanghao);
61 }
62 }
63 hanghao++;
64 }
65 }
66 auto a = make_shared<vector<string>>(d);
67 auto b = make_shared<map<string, set<int>>>(m);;
68 data = a;
69 mp = b;
70 }
71
72 QueryResult TextQuery::query(string s)
73 {
74 QueryResult qr;
75 auto p = (*mp).find(s);
76 if (p == (*mp).end())
77 {
78 return qr;
79 }
80 else
81 {
82 qr.frequence = p->second.size();
83 auto q = p->second.begin();
84 auto ed = p->second.end();
85 int i = 0;
86 while (q != ed)
87 {
88 qr.hanghao[i] = *q;
89 qr.text[i] = (*data)[*q];
90 i++;
91 q++;
92 }
93 return qr;
94 }
95 }
96
97 ostream &print(ostream& c, QueryResult q)
98 {
99 c << "该单词出现了" << q.frequence << "次" << endl;
100 int i = 0;
101 while (q.hanghao[i] != 0)
102 {
103 c << "出现在第" << q.hanghao[i] << "行" << "的内容为:" << q.text[i] << endl;
104 i++;
105 }
106 return c;
107 }
108
109 void runQueries(ifstream& infile)
110 {
111 TextQuery tq(infile);
112 while (true)
113 {
114 cout << "请输入某个单词进行查询,或输入q进行退出:";
115 string s;
116 if (!(cin >> s) || s == "q") break;
117 print(cout, tq.query(s)) << endl;
118 }
119 }
120
121 int main()
122 {
123 ifstream out;
124 out.open("C:\\Users\\Administrator\\Desktop\\c\\data.txt");
125 if (out)
126 {
127 //条件成立,则说明文件打开成功
128 cout << "endless.txt open scessful" << endl;
129 }
130 else
131 cout << "endless.txt doesn't exist" << endl;
132 runQueries(out);
133 out.close();
134 }
实验结果
