统计文件中不小于某一长度的单词的个数(泛型算法实现)

#include<iostream>
#include<fstream>
#include<vector>
#include<string>
#include<algorithm>
#include<cstdlib>
using namespace std;

ifstream & openFile(ifstream &in,const string &fileName)
{
	in.close();
	in.clear();
	in.open(fileName.c_str());
	return in;
}

bool isShorter(const string &s1,const string &s2)
{
	//predicate function
	return s1.size()<s2.size();
}

bool GT6(const string &s)
{
	//predicate function
	return s.size()>=6;
}

int main(int argc,char *argv[])
{
	ifstream inFile;
	if(argc<2 || !openFile(inFile,argv[1]))
	{
		cerr<<"No input file!"<<endl;
		return EXIT_FAILURE;
	}

	//words 存储目标文件
	vector<string> words;
	string word;
	while(inFile>>word)
		words.push_back(word);

	//去除重复
	sort(words.begin(),words.end());  //排序
	vector<string>::iterator endUnique=unique(words.begin(),words.end());  //endUnique指向非重复元素末端的下一位置
	words.erase(endUnique,words.end());  //删除重复的元素

	stable_sort(words.begin(),words.end(),isShorter);  //按单词的长度再一次排序

	vector<string>::size_type wc=count_if(words.begin(),words.end(),GT6); //统计长度不小于6单词的个数

	cout<<wc<<' '<<(wc<2?"word":"words")<<" 6 alphabets or longer:"<<endl;
	for(vector<string>::iterator it=words.begin();it!=words.end();++it)
		if(GT6(*it))
			cout<<*it<<endl;
	cout<<endl;

	return EXIT_SUCCESS;
}

你可能感兴趣的:(Algorithm,文件,generic,单词个数)