//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;
}
C++ Primer 第10章 习题10.23
最新推荐文章于 2024-09-16 17:46:36 发布