统计单词频率--map

问题描述:

输入一个单词列表,每行一个单词,统计单词出现的频率

思路:

主要是使用c++中的map容器。map实质上是一个二叉查找树,可以做到插入、删除、查询,平均查询时间在O(logn)。n为map中元素的个数,将字符串数据插入到map后,再用迭代器去访问map中的元素时,其实是按照map中插入的字符串的字典序进行访问的。

map可以建立任意两种数据类型的关系,形式为map<type1,type2>map1。type1表示键key,type2表示值value。键是用来进行索引。

源代码:

 1 #include <iostream>
 2 #include <string>
 3 #include <map>
 4 using namespace std;
 5 
 6 int main()
 7 {
 8     string word;  //输入单词
 9     int  amount = 0;  //单词总数
10     map<string, int> word_count;
11     while(cin>>word)
12     {
13         word_count[word]++;
14         amount++;
15     }
16     cout.setf(ios::fixed);//以定点形式表示浮点数
17     cout.precision(4);//设置小数部分的有效数字
18     map<string, int>::iterator it = word_count.begin();
19     while( it != word_count.end())
20     {
21         double rate =100*(double) it->second / amount;
22         cout << it->first << " "<< rate <<"%"<<endl;
23         it++;
24     }
25     return 0;
26 }

 

posted @ 2015-01-27 16:59  希隆囚徒  阅读(248)  评论(0编辑  收藏  举报