Posted on 2010-07-10 21:36
FuthorclySLM 阅读(559)
评论(0) 编辑 收藏 引用 所属分类:
ACMer
今天背单词的时候突然想到的,觉得挺实用的,就回来敲了一个,在code::blocks下成功运行,在VC下要将_fcloseall()函数改成fcloseall(),这个程序的效率可能不是最高的,空间的耗费很大(因为用了map和vector),就当是巩固一下STL的知识了。使用的时候将英语文章(可以一次存很多篇)拷贝到一个记事本里面,然后命名为 word_in.txt ,放在程序的根目录下,之后的结果存在word_out.txt里面。
1 #include<iostream>
2 #include<algorithm>
3 #include<iomanip>
4 #include<stdio.h>
5 #include<stdlib.h>
6 #include<cctype>
7 #include<vector>
8 #include<utility>
9 #include<string>
10 #include<map>
11 using namespace std;
12
13 void cpy(map<string,int> & words , vector<pair<string, int> > & ws )
14 {
15 pair<string,int> tmp;
16 for(map<string,int>::iterator i = words.begin() ; i != words.end() ; ++i)
17 {
18 tmp = make_pair( i -> first , i -> second);
19 ws.push_back(tmp);
20 }
21 }
22 void init_word_list()
23 {
24 FILE *fp = fopen("word_in.txt","r");
25 FILE *fout = fopen("word_tmp.txt","w");
26 char ch;
27 while(!feof(fp))
28 {
29 ch = fgetc(fp);
30 if(islower(ch) || ch == ' ') fputc(ch,fout);
31 else if(isupper(ch)) fputc('a'+ch - 'A' , fout);
32 }
33 if(_fcloseall( )) cout << "Congratulation! Words list init sucess!" <<endl;
34 }
35 bool value_cmp(pair<string,int> a, pair<string,int> b)
36 {
37 return a.second > b.second;
38 }
39 int main()
40 {
41 init_word_list();
42 freopen("word_tmp.txt","r",stdin);
43 freopen("word_out.txt","w",stdout);
44 map<string,int> word ;
45 vector<pair<string,int> > wd;
46 string tmp;
47 while(cin >> tmp) word[tmp]++;
48 cpy(word,wd);
49 stable_sort(wd.begin() , wd.end() , value_cmp);
50
51 for(vector<pair<string,int> > :: iterator i = wd.begin() ; i != wd.end() ; ++i)
52 {
53 cout <<"|"<<left<< setw(20)<<(*i).first <<(*i).second<<endl;
54 }
55 return 0;
56 }
57