zoukankan      html  css  js  c++  java
  • 使用标准库:文本查询程序

    使用标准库:文本查询程序

    class QueryResult
    {
    friend  std::ostream& print(std::ostream&,cost QueryResult&);
    public:
    	Queryresult(std::string s,
    				std::shared_ptr<std::set<line_no>> p,
    				std::shared_ptr<std::vector<std::string>>f):
    				sought(s),lines(p),file(f){ }
    private:
    	std::string sought;		//查询单词
    	std::shared_ptr<std::set<line_no>> lines;		// 出现的行号
    	std::shared_ptr<std::vector<std::string>> file;		// 输入文件
    
    };
    
    class TextQuery{
    pulic:
    	using line_no = std::vector<std::string>::size_type;
    	TextQuery(std::ifstream&);
    	QueryResult query(const std::strng&) const;
    private:
    	std::shared_ptr<std::vector<std::string>> file;
    	std::map<std::string,std::shared_ptr<std::set<line_no>>> wm;
    };
    
    TextQuery::TextQuery(iftream& is):file(new vector<string>)
    {
    	string text;
    	while(getline(is,text))		//  对文件中的每一行
    	{
    		file->push_back(text);	// 保存文本
    		int n = file->size() - 1;	// 保存当前行号
    		istringstream line(text);	// 将行文本拆解为单词
    		string word;
    		while(line >> word)
    		{
    			// 如果这个单词不在vm中,以下标在vm中添加一项
    			auto& lines = wm[word];		// lines 是一个shared_ptr
    			if(!lines)	// 如果第一次遇到这个单词,此指针为空
    				lines.reset(new set<line_no>);
    			lines->insert(n);	// 将此行号插入到 set 中
    		}		
    	}
    }
    
    QueryResult TextQuery::query(const string& sought) const
    {
    	static shared_ptr<set<line_np>> nodata(new set<line_no>);
    	auto loc = wm.find(sought);
    	if(loc == wm.end())
    		return QueryResult(sought,nodata,file);
    	else
    		return QueryResult(sought,loc->second,file);
    }
    
    ostream &print(ostream& os,const QueryResult& qr)
    {
    	os<<qr.sought<<"occurs " << qr.lines->size()<<" "<<make_plural(qr.lines->size(),"times","s")<<endl;
    	for(auto num : *qr.lines)
    		os <<"	(line"<<num+1<<")"<<*(qr.file->begin()+num)<<endl;
    	
    	return os;
    }
    
  • 相关阅读:
    CSS之EM相对单位
    html之canvas
    JS之事件监听
    html之iframe
    [转]nodejs中的process模块--child_process.exec
    [转]阮一峰:理解RESTful架构
    JS性能之滚动条之外的其他部分
    JS性能之setTimeout与clearTimeout
    CSS禁止鼠标事件---pointer-events:none
    打开文件、文件操作、管理上下文
  • 原文地址:https://www.cnblogs.com/xiaojianliu/p/12496833.html
Copyright © 2011-2022 走看看