C++ primer TextQuery 和QueryResult来实现单词查找功能

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 }
实验结果
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理