zoukankan      html  css  js  c++  java
  • 统计单词频率--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 }
  • 相关阅读:
    js通过class获取元素时的兼容性解决方案
    html5的八大特性
    typeof与instanceof的区别
    evel()与JSON.parset()的区别
    apt-get出现的问题
    Linux下开启计划任务日志
    ls
    win10自带IE上不了网的解决办法
    crontab -e文件存放路径
    Linux系统下面crontab选择默认编译器
  • 原文地址:https://www.cnblogs.com/xlzhh/p/4253438.html
Copyright © 2011-2022 走看看