统计单词频率--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 }

 

转载于:https://www.cnblogs.com/xlzhh/p/4253438.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值