C++ Primer 第五版 中文版 练习 12.27 个人code

C++ Primer 第五版 中文版 练习 12.27

题目:TextQuery 和 QueryResult 类只使用了我们已经介绍过的语言和标准库特性。不要提前看后续章节内容,

只用已经学到的知识对这两个类编写你自己的版本。

答:

下面是我自己写的两个类……那个查询功能 不知道怎么写……写了点觉得不对,就注释掉了,也没有用到智能指针。

由于那个查询返回的内容我不知道如何安排,所以QueryResult类的成员函数 print 也没有定义……。


TextQuery.h

/*
类名:TextQuery
成员:包含一个vector、一个map和一个set。
	  vector用来保存输入文本
	  map用来关联每个单词和它出现的行号的set。
	  set保存行号。

*/
#ifndef TEXT_QUERY_H
#define TEXT_QUERY_H


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


class TextQuery
{
public:
	friend class QueryResult;
	TextQuery();
	TextQuery(std::ifstream &inputfile); //重载构造函数,接受一个文件流保存,生成对象。
	QueryResult query(const std::string &s);  //查询map成员,返回查询结果。
	~TextQuery();

private:
	std::vector<std::string> filetext;  //按行保存输入文本
	std::map < std::string, std::set<unsigned>> wordinlinenum; //关联每个单词和它出现的行号的set。

};

#endif
TextQuery.cpp

#include "TextQuery.h"
#include "QueryResult.h"

TextQuery::TextQuery()
{
}

TextQuery::~TextQuery()
{
}

//定义构造函数,读取文件流,并保存每个单词和单词对应的行号。
TextQuery::TextQuery(std::ifstream &inputfile)
{
	std::string line,word;
	if (inputfile)
	{
		while (!inputfile.eof())
		{
			std::getline(inputfile, line);
			filetext.push_back(line);	
		}
	}
	for (std::vector<std::string>::size_type i = 0; i != filetext.size(); ++i)
	{
		std::istringstream line2word(filetext[i]);
		while (line2word >> word)
		{
			wordinlinenum[word].insert(i);
		}
	}
}

//查询并返回
QueryResult TextQuery::query(const std::string &s)
{
	//QueryResult myqueryresult;
	//auto iter = wordinlinenum.find(s);
	//this->s = s;
	//this->linenum = iter->second;
	//return *this;
}

QueryResult.h

#ifndef QUERY_RESULT_H
#define QUERY_RESULT_H


#include "TextQuery.h"

class QueryResult
{
public:
	QueryResult() = default;
	QueryResult(TextQuery &mytq) :s(mytq.s), count(mytq.count), linenum(mytq.linenum), linetext(mytq.linetext) {}
	void print(std::ostream &out, QueryResult &qr); //打印结果。
private:
	std::string s;  //查找的单词。
	unsigned count; //出现的次数。
	std::set<unsigned> linenum; //出现的行号。
	std::vector<std::string> linetext;//所在行的整行文本内容。
};

#endif // !QUERY_RESULT_H


QueryResult.cpp

#include "QueryResult.h"

void QueryResult::print(std::ostream &out, QueryResult &qr)
{


}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值