码迷,mamicode.com
首页 > 其他好文 > 详细

文本查询程序——标准库学习小结

时间:2017-11-17 22:26:06      阅读:98      评论:0      收藏:0      [点我收藏+]

标签:一个   cout   make   file   str   push   iostream   har   span   

程序:允许用户在一个给定文件中查询单词,查询结果是单词在文件中出现的次数及其所在行的列表。如果一个单词在一行中出现多次,此行只列出一次。

#include <iostream>
#include <fstream>
#include <sstream>
#include <memory>
#include <map>
#include <set>
#include <vector>
#include <string>

using namespace std; 

class QueryResult;
//保存输入文件 
class TextQuery {
	using lineNo = vector<string>::size_type;
public:
	TextQuery(ifstream &is);
	QueryResult query(const string&) const;
private:
	shared_ptr<vector<string>> file;
	map<string, shared_ptr<set<lineNo>>> imap;
};

//保存查询结果 
class QueryResult {
	using lineNo = vector<string>::size_type;
	friend ostream& operator<<(ostream&, const QueryResult&);
public:
	QueryResult(const string &s, shared_ptr<vector<string>> f, shared_ptr<set<lineNo>> l) :sword(s), file(f), line(l) {}
private:
	string sword;
	shared_ptr<vector<string>> file;
	shared_ptr<set<lineNo>> line;
};

TextQuery::TextQuery(ifstream &is) :file(make_shared<vector<string>>())
{
	string line;
	while (getline(is, line)) {
		file->push_back(line);
		istringstream in(line);
		auto l = file->size() - 1;
		string word;
		while (in >> word) {
			shared_ptr<set<lineNo>> &r = imap[word];
			if (!r)
				r.reset(new set<lineNo>);
			r->insert(l);
		}
	}
}

QueryResult TextQuery::query(const string &word) const
{
	static shared_ptr<set<lineNo>> nodata(new set<lineNo>);
	auto it = imap.find(word);
	if (it != imap.end())
		return QueryResult(word, file, it->second);
	else
		return QueryResult(word, file, nodata);
}

ostream& operator<<(ostream &os, const QueryResult &qr)
{
	auto cnt = qr.line->size();
	os << qr.sword << " occurs " << cnt << (cnt > 1 ? " times" : " time") << endl;
	for (auto l : *qr.line) {
		os << "\t(line " << l + 1 << ") " << *(qr.file->begin() + l) << endl; 
	}
	return os;
}

int main()  
{  
	ifstream in("data.txt");
	TextQuery tq(in);
	cout << "请输入要查询的单词:\n";
	string s;
	while (cin >> s) {
		cout << tq.query(s) << endl;
		cout << "请输入要查询的单词:\n";
	}
	return 0;
}

  

文本查询程序——标准库学习小结

标签:一个   cout   make   file   str   push   iostream   har   span   

原文地址:http://www.cnblogs.com/xzxl/p/7853583.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!