#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强制类型转换: