c++——容器实现文本查询程序

/*vs2010编译通过*/
/*缺点:无大小写区分,没有剔除标点符号*/
/*Search.h*/
#pragma once
#include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <set>
#include <vector>
#include <utility>
#include <stdexcept>
#include <sstream>
using namespace std;
class CSearch
{
public:
	CSearch(void);
	void OpenFile(const string  fname);
	void MakeMap();
	void Search(const string key_word);
	void ShowResult() const;
	~CSearch(void); 

private:
	int m_lineCount;
	int m_wordCount;
	ifstream m_ifs;
	vector<string> m_lineVec;
	map< int, vector<string> > m_wordMap;
	set<int> m_resultSet;
};


/*Search.cpp*/
#include "StdAfx.h"
#include "Search.h"


CSearch::CSearch(void)
{
	m_lineCount = 0;
	m_wordCount = 0;
}

void CSearch::OpenFile(const string  fname)
{
	m_ifs.open(fname.c_str(), ifstream::in);
	if (!m_ifs)
		throw runtime_error("文件打开失败!");
}

void CSearch::MakeMap()
{
	string strLine;
	while (getline(m_ifs, strLine))
	{
		++m_lineCount;
		m_lineVec.push_back(strLine);
		istringstream iss(strLine);
		string tempWord;
		vector<string> word_vec;
		while (iss >> tempWord)
		{
			word_vec.push_back(tempWord); 
		}
		m_wordMap.insert(make_pair(m_lineCount, word_vec));
		word_vec.clear();
	}
}

void CSearch::Search(const string key_word)
{
	map< int, vector<string> >::const_iterator map_it = m_wordMap.begin();
	while (map_it != m_wordMap.end())
	{
		int flag = 0;
		vector<string>::const_iterator vec_it = (*map_it).second.begin();
		for ( ; vec_it != (*map_it).second.end(); ++vec_it)
		{
			if (key_word == *vec_it)
			{
				++m_wordCount;
				flag = 1;
			}
		}
		if (flag)
			m_resultSet.insert((*map_it).first);
		++map_it;
	}
}

void CSearch::ShowResult() const
{
	cout << "找到匹配单词:" << m_wordCount << endl;
	set<int>::const_iterator set_it = m_resultSet.begin();
	while (set_it != m_resultSet.end())
	{
		cout << "第" << *set_it << "行" << " " << m_lineVec[*set_it - 1] << endl;
		++set_it;
	}
}

CSearch::~CSearch(void)
{
}

// SearchWords.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "Search.h"

int _tmain(int argc, _TCHAR* argv[])
{
	CSearch mySearch;
	try
	{
		mySearch.OpenFile("article.txt");
	}
	catch (runtime_error err)
	{
		cout << err.what() << endl;
		return 0;
	}
	mySearch.MakeMap();
	cout << "请输入要查找的单词:";
	string key_word;
	cin >> key_word;
	mySearch.Search(key_word);
	mySearch.ShowResult();

	return 0;
}            


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值