C++ Primer 第10章 习题10.23

//10.23.cpp
//编写程序将被排除的单词存储在vector对象中,而不是存储在set对象中
//函数restricted_wc,根据形参指定文件建立单词排除集
//将被排除的单词存储在vector对象中,
//并从标准输入设备读入文本,对不在排除集中的单词进行出现次数统计
//主函数例示restricted_wc函数的使用
#include<iostream>
#include<fstream>
#include<map>
#include<vector>
#include<string>
using namespace std;

void restricted_wc(ifstream &removeFile,
					map<string,int>&wordCount)
{
	vector<string> excluded;	//保存被排除的单词
	string removeWord;
	while(removeFile>>removeWord)
		excluded.push_back(removeWord);
	//读入文本并对不在排除集中的单词进行出现次数统计
	cout<<"Enter text(Ctrl-z to end):"<<endl;
	string word;
	while(cin>>word)
	{
		bool find=false;

		//确定该单词是否在排除集中
		vector<string>::iterator iter=excluded.begin();
		while(iter!=excluded.end())
		{
			if(*iter==word)
			{
				find=true;
				break;
			}
			++iter;
		}
		//如果单词不在排除集中,则进行计数
		if(!find)
			++wordCount[word];
	}
}

int main()
{
	map<string,int> wordCount;
	string fileName;

	//读入包含单词排除集的文件的名字并打开相应文件
	cout<<"Enter filename:"<<endl;
	cin>>fileName;
	ifstream exFile(fileName.c_str());
	if(!exFile)//打开文件失败
	{
		cout<<"error: can not open file:" <<fileName<<endl;
		return -1;
	}

	//调用restricted_wc函数
	//对输入文本中不在排除集中的单词进行出现次数统计
	restricted_wc(exFile,wordCount);

	//输出统计结果
	cout<<"word\t\t"<<"times"<<endl;
	map<string,int>::iterator iter=wordCount.begin();
	while(iter!=wordCount.end())
	{
		cout<<iter->first<<"\t\t"<<iter->second<<endl;
		iter++;
	}
	cout<<endl;
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小巫技术博客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值