博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
编程珠玑:单词频率最高选取
阅读量:6891 次
发布时间:2019-06-27

本文共 2094 字,大约阅读时间需要 6 分钟。

问题描述:

对一个输入文本中的每个单词的出现次数统计,并选取出现频率最大的10个单词

 

首先用C++实现,着重注意STL的map,vector排序用法,这里与编程珠玑的代码不同。不知道何故,编程珠玑上的代码, 输入之后得到的结果是按照单词排序的,而不是按照次数排序,这里做了修改

C++实现代码:

#include 
#include
#include
#include
#include
#include
using namespace std; typedef pair
PAIR;int cmp(const PAIR& x, const PAIR& y){ return x.second > y.second;} int main() { map
wordcount; vector
vec; vector
::iterator itr; string t; while((cin >> t) && t != "0") { wordcount[t]++; } for (map
::iterator curr = wordcount.begin(); curr != wordcount.end(); ++curr) { vec.push_back(make_pair(curr->first, curr->second)); } sort(vec.begin(), vec.end(), cmp); for(itr = vec.begin(); itr != vec.end(); itr++) { cout << itr->first << " " << itr->second<

 

这里用C语言试下的话较为麻烦些,需要建立自己的节点和散列表:

下面按照编程珠玑,用C语言实现,但是编程珠玑似乎仍然没有给出排序的方式

#include 
#include
#include
#define NHASH 29989#define MULT 31typedef struct node{ char *word; int times; node *next;} node;typedef struct node *nodeptr;nodeptr bin[NHASH];int hash(char *p){ unsigned int h = 0; for( ; *p != 0; p++) { h = h * MULT + *p; if(h > NHASH) { h = h % NHASH; } } return h;}void incWord(char *s){ int h = hash(s); for(node *p = bin[h]; p != NULL; p = p->next) { if(strcmp(s,p->word) == 0) { p->times++; return ; } } node *ptr ; ptr = (node*)malloc(sizeof(node)); ptr->times = 1; ptr->word = (char*)malloc(strlen(s)+1); strcpy(ptr->word, s); ptr->next = bin[h]; bin[h] = ptr;}int main(){ char buf[50]; while(scanf("%s", buf) != EOF ) { incWord(buf); } for(int i=0; i
next) { printf("%s %d\n", p->word, p->times); } } for(int i=0; i
next) { free(p); } } system("pause");}

 

转载于:https://www.cnblogs.com/biyeymyhjob/archive/2012/08/14/2636950.html

你可能感兴趣的文章
把“数字的字符串”转换成“整数”时遇到的小麻烦
查看>>
消耗系统内存
查看>>
mysql-connector-c++ 编译安装
查看>>
A - Space Elevator(动态规划专项)
查看>>
C语言之数组与指针的易混淆知识点
查看>>
MakeFile 文件的使用
查看>>
css绝对居中img
查看>>
mysql使用存储过程和event定期删除
查看>>
基于python3+opencv3图像基础IO操作
查看>>
(旧)子数涵数·PS ——翻页效果
查看>>
Day2 Excel与数据处理之定位条件、选择性粘贴及查找功能
查看>>
npm install 时间很长解决方案
查看>>
搭建maven环境
查看>>
中国大学MOOC-C程序设计(浙大翁恺)—— 时间换算
查看>>
爬豆瓣电影名
查看>>
深度学习之各种网络结构
查看>>
leetcode20: Insert Interval
查看>>
GNU make: Learning notes
查看>>
泛型程序设计---泛型方法的定义
查看>>
一个“MacBook”新手的Python“笨办法”自学之旅 #第九章:Python的函数
查看>>