当前位置:C++技术网 > 资讯 > STL算法实现得到电脑中的某个文件中的所有字符的个数

STL算法实现得到电脑中的某个文件中的所有字符的个数

更新时间:2016-04-18 22:21:04浏览次数:1+次

查询文件中的字符的个数。首先,新建一个txt文件,而后,写一些字符(对于本文的代码,你可以查询我写的STL的文章,主要是map,count函数的文章):

看看实现:

#include "stdio.h"
#include "windows.h"
#include "fstream"
#include "iostream"
#include "string"
#include "iterator"
#include "algorithm"
#include "vector"
#include "map"

using namespace std;

int main()
{
	cout<<"请输入需要打开的文件的路径"<<endl;
	
	string FilePath;

	cin>>FilePath;
	ifstream in(FilePath,ios::binary);//输入要读取的文件名,并打开它
	if(!in.is_open())
	{
		cout<<"打开失败!"<<endl;
	}
	else
	{
		istream_iterator<char> read_in(in),eof;
	
		vector<char> coll;
		copy(read_in,eof,back_inserter(coll));//将文件都复制拷贝到coll中

		sort(coll.begin(),coll.end());//排序文件中的数据,以便最后的移除函数操作

		map<char, int> counts;//创建映射结构,将单词与数量隔开
		char word;
		
		for(int i=0; i<coll.size(); i++)
		{
			word=coll.at(i);
			++counts[word];
		}
		
		vector<char> vec;

		vector<char>::iterator pos=unique(coll.begin(),coll.end());//实现将文件中的重复的数据移除掉,基于已序操作
		copy(coll.begin(),pos,back_inserter(vec));//将unique函数的返回值作为另一vector的结束位置
		 
		//copy(coll.begin(),pos,ostream_iterator<char>(cout,""));//输出测试
		//cout<<endl;

		for(int i=0; i<vec.size(); i++)
		{
			char cha=vec.at(i);
			map<char, int>::iterator num(counts.find(cha));//map数据结构的查询算法

			if(num==counts.end())
			{
				cout<<"出错!"<<endl;
			}
			else
			{
				cout<<num->first<<" ";//输出单词
				cout<<num->second;//输出计数
				cout<<endl;
			}
		}
		cout<<endl;
	}
	system("pause");
	return 0;
}