习题5.13 词频统计 (30 分)

#include <stdio.h>
#include <string.h>
#include<iostream>
#include<vector>
#include<string>
#include<unordered_map>
#include<algorithm>
using namespace std;
bool JudgeChar(char c);
unordered_map<string, int>Hash;
class item {
public:

	string s;
	int frequency;
	item(string s1,int t)
	{
		s = s1;
		frequency = t;
	}
	bool operator<(const item&a)const
	{
		if (frequency > a.frequency)
		{
			return true;
		}
		else if (frequency == a.frequency)
		{
			if (s < a.s)//输出字母序小的
			{
				return true;
			}
		}
		return false;

	}
};
int main()
{
	string str;
	char c;
	while (cin.peek() != '#')
	{
		if (JudgeChar(cin.peek()))
		{
			c = cin.get();
			if (c >= 'A' && c <= 'Z')//变小写
			{
				c = c | 0x20;
			}
			str =str+c;
		}
		else
		{
			if (str.size() >= 1 && str.size() <= 80)//不超过80个
			{
				if (str.size() > 15)
				{
					str = str.substr(0, 15);
				}
				Hash[str]++;
				str = "";

			}
			cin.get();

		}
	}
	if (str.size()>=1&&str.size() <= 80)//this#不超过80个
	{
		Hash[str]++;
		cin.get();
	}
	vector<item>v;
	for (auto i : Hash)
	{
		v.push_back({ i.first,i.second });
	}
	sort(v.begin(), v.end());
	printf("%d\n", v.size());
	int size = v.size() * 0.1;/*整型与浮点数转换 */
	for (int i = 0; i < size; i++)
	{
		cout << v[i].frequency << ':' << v[i].s << endl;
	}
}
bool JudgeChar(char c)
{
	if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || (c == '_'))
	{
		return true;
	}
	else
	{
		return false;
	}
}

收获
1 输入的时候把字符输入到缓冲区里,按回车后才开始读取缓冲区里的数字,没读取完之前没法输入
2从’0’到’9’
3sort比较函数中 invalid conparator
对于任一变量a,comp(a,a)为false
如果comp(a,b) 为true,那么comp(b,a)为false
如果comp(a,b)为true且comp(b,c)true,则comp(a,c)为true
4:如何使用sort:可以重载<
5:substr提取字符串
7强制类型转换:
在这里插入图片描述
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值