这是《C++ primer》中的一个示例程序,看了几遍仍觉有些细节没有明白,故手敲了一遍
需了解STL容器部分知识点,智能指针,文件流,string流
《C++ primer》文本查询程序一
书上给的例子尚有瑕疵,如果单词在同一行出现多次,则只会记录为一次,本人能力有限,尚未解决此问题
以下是写完程序后绘制的思维导图
![image-20240413155500846]()
代码部分
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| #include<iostream> #include<fstream> #include"TextQuery.h" #include"ResultQuery.h" using namespace std;
void runQueries(ifstream& fin);
int main(void) { string filename; cout << "请输入你要查询的文件名(包含后缀)"<<endl; cin >> filename; ifstream readFile(filename, ios::in); if (readFile.is_open()) { runQueries(readFile); } else cout << "the file open failed!!!" << endl; }
void runQueries(ifstream& fin) { TextQuery tq(fin); while (1) { cout << "please enter word to look for, or q to quit." << endl; string needle; if (cin >> needle && needle != "q" && needle != "Q") { MyPrint(cout, tq.query(needle)) << endl; } else break; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| #pragma once #include<memory> #include<string> #include<map> #include<set> #include<vector> #include"ResultQuery.h"
using namespace std;
class TextQuery { private: shared_ptr<vector<string>> file; map<string, shared_ptr<set<int>>> wm; public: TextQuery(ifstream& fin); ResultQuery query(string needle); };
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| #include "TextQuery.h" #include<string> #include<sstream> #include<fstream> using namespace std; TextQuery::TextQuery(ifstream& fin):file(new vector<string>) { string lineContent; size_t lineNo; while(getline(fin,lineContent)) { file->push_back(lineContent); lineNo = file->size() - 1; istringstream line(lineContent); string word; while (line >> word) { shared_ptr<set<int>>& NO = wm[word]; if (!NO) { NO.reset(new set<int>); NO->insert(lineNo); } else NO->insert(lineNo); } } }
ResultQuery TextQuery::query(string needle) { shared_ptr<set<int>> nothing (new set<int>); auto result = wm.find(needle); if (result == wm.end()) { return ResultQuery(needle,file, nothing); } else { return ResultQuery(needle,file, result->second); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| #pragma once #include<memory> #include<string> #include<vector> #include<set> #include<map> using namespace std; class ResultQuery { private: string needle; shared_ptr<vector<string>> file; shared_ptr<set<int>> lines; public: ResultQuery(string n, shared_ptr<vector<string>> f, shared_ptr<set<int>> l) :\ needle(n), file(f), lines(l) {} friend ostream& MyPrint(ostream&, const ResultQuery&); };
|
1 2 3 4 5 6 7 8 9 10
| #include "ResultQuery.h" #include <iostream> ostream& MyPrint(ostream& os, const ResultQuery& rq) { os<< rq.needle << " occurs " << rq.lines->size() << "times in the file " << endl; for (auto line : *(rq.lines)) { os << "\tline:"<<line+1<< " "<<rq.file->begin()[line]<<endl; } return os; }
|