C++简单实现文本查询程序
/* * @Author: CY__HHH * @Date: 2020-04-17 00:27:19 * @LastEditTime: 2020-07-02 15:07:15 */ #include<bits/stdc++.h> #define rep(i, n) for(int i=0;i!=n;++i) #define per(i, n) for(int i=n-1;i>=0;--i) #define Rep(i, sta, n) for(int i=sta;i!=n;++i) #define rep1(i, n) for(int i=1;i<=n;++i) #define per1(i, n) for(int i=n;i>=1;--i) #define Rep1(i, sta, n) for(int i=sta;i<=n;++i) #define L rt<<1 #define R rt<<1|1 #define inf (0x3f3f3f3f) #define llinf (1e18) #define ALL(A) A.begin(),A.end() #define SIZE(A) ((int)A.size()) #define MOD (1e9 + 7) #define PII pair<int,int> typedef long long i64; using namespace std; class QureyResult{ public: friend ostream &print(ostream &os,const QureyResult &result) { os << result.words << "occurs " << result.lines->size() << "times" << endl; for(auto &pos:*(result.lines)){ os << "line " << pos + 1 << " "; os << (*result.TEXT)[pos] << endl;//输出对应的行 } return os; } QureyResult(string s,shared_ptr<set<int>> p,shared_ptr<vector<string>> f) :words(s),lines(p),TEXT(f){} private: string words;//query words shared_ptr<vector<string>> TEXT;//共享内存 shared_ptr<set<int>> lines;//出现的行号 };//返回查询的结果 class TextQuery{ public: TextQuery(ifstream &infile):TEXT(new vector<string>) { string line,words; int lineNum = 0; while(infile){ getline(infile,line); TEXT->push_back(line); istringstream instring(line); while(instring){ instring >> words; auto &tempPtr = dict[words];//shared_ptr if(!tempPtr) tempPtr.reset(new set<int>);//不在dict中则分配内存 tempPtr->insert(lineNum); } ++lineNum;//行号加一 } } QureyResult query(string &str)const //返回一个查询结果 { static shared_ptr<set<int>> p(new set<int>);//未找到值是返回 auto tmp = dict.find(str);//tmp 为str对应的pair if(tmp == dict.end()) return QureyResult(str,p,TEXT); else return QureyResult(str,tmp->second,TEXT); } private: shared_ptr<vector<string>> TEXT;//保存文本信息 分享动态内存 map<string,shared_ptr<set<int>>> dict;//每个单词出现的行号 }; void runQueries(ifstream &infile) { TextQuery tq(infile); while(true){ cout << "enter word to look for, or q to quit: "; string s; if(!(cin >> s) || s == "q") break; print(cout,tq.query(s)) << endl; } } int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); ifstream in("1.txt"); runQueries(in); return 0; }
不怕万人阻挡,只怕自己投降。
posted on 2020-07-02 15:11 chengyulala 阅读(320) 评论(0) 编辑 收藏 举报