之前有一个需求:统计一个混合中英文字符和各种符号的文件的各字符数量,结果发现,事情并没有想象的那么简单.于是先写个只统计英文字符的程序吧.    1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47//data.txt需要放在相同目录下
//只能计算纯英文文件中的字符.
using namespace std;
int main(){
	ifstream infile("data.txt");
	string s1;
	char c;
	map<char,int> m1;
	multimap<double,char> m2;
	int sumchar=0;
	
	clock_t start,end;
	start=clock();
	while(infile.get(c)){
		m1[c]++;
		sumchar++;
	}
	
	std::map<char,int>::iterator it1=m1.begin();
	for(;it1 != m1.end(); it1++){
		m2.insert(pair<double,char>((it1->second*1.0/sumchar),it1->first));
	}
	
	end=clock();
	cout<<"共计:"<<(end-start)/1000<<"毫秒"<<endl;
	//cout<<(end-start)/CLOCKS_PER_SEC<<"秒"<<endl;
	cout<<"总计:"<<sumchar<<"个字符"<<endl<<endl;
	
	
	std::multimap<double,char>::iterator it2=m2.begin();
	for(;it2 != m2.end();it2++){
		cout<<it2->second<<" "
			<<setw(4)<<it2->first*100<<"%"
			<<endl;
	}
}
知识点
- c++中给map按值排序
- C++获取时间间隔
欢迎与我分享你的看法。
转载请注明出处:http://taowusheng.cn/