慕课-(程序设计实习)---STL(map例题)单词词频统计

本文介绍了一款用于统计大量单词出现频率的程序。该程序能够接收大量单词输入,每个单词一行,长度不超过20字符,并且没有空格。程序会统计每个单词的出现次数,并按出现次数从多到少输出这些单词及其出现次数。当出现次数相同时,字典序靠前的单词将排在前面。通过使用C++中的map和set数据结构,实现了高效的数据处理和排序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

单词词频统计程序


输入大量单词,每个单词,一行,不超过20字符,没有 空格。 按出现次数从多到少输出这些单词及其出现次数 。出现次数相同的,字典序靠前的在前面。

输入样例:

this

is

ok

this

plus

that

is

plus

plus

输出样例:

plus 3

is 2

this 2

ok 1

that 1

代码:

#include<iostream>
#include<cstdio>
#include<set>
#include<map>
#include<algorithm>
#include<cstring>
using namespace std;
struct word
{
    string wd;
    int time;
};
struct rule
{
    bool operator()(const word &w1,const word &w2)
    {
        if(w1.time!=w2.time)
            return w1.time>w2.time;
        else
            return w1.wd<w2.wd;
    }
};
int main()
{
    ios::sync_with_stdio(false);
//    freopen("in.txt","r",stdin);
    string s;
    map<string,int> mp;
    set<word,rule> st;
    map<string,int>::iterator p;
    set<word,rule>::iterator i;
    while(cin>>s)
    {
        mp[s]++;
    }
    for(p=mp.begin();p!=mp.end();p++)
    {
        word tmp;
        tmp.wd=p->first;
        tmp.time=p->second;
        st.insert(tmp);
    }
    for(i=st.begin();i!=st.end();i++)
        cout<<i->wd<<" "<<i->time<<endl;
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值