C++统计单词个数及排序:容器按照value排序

本文介绍了一种用于统计英文文本中单词出现频率的算法,并通过C++实现该算法。算法首先读取文件中的所有单词,然后使用哈希表记录每个单词出现的次数,最后根据单词出现次数及字母顺序进行排序。
部署运行你感兴趣的模型镜像

例:

给定一段英语文本,要求对其中单词出现的个数按照从小到大进行排序,出现次数相同的按照首字母顺序排列。

算法实现:

#include <iostream>
#include <algorithm>
#include <vector>
#include <unordered_map>
#include <map>
#include <fstream>

using namespace std;
typedef pair<string, int> PAIR;

int cmp(const PAIR &x, const PAIR &y) {
    return x.second < y.second;
}

int main() {
    string file;
    cout << "Enter the text path:";
    cin >> file;
    ifstream inout;
    inout.open(file, ios::in);

    if (inout.fail()) {
        cout << "Your file don't exist!" << endl;
        return 0;
    }
    vector<string> key;
    map<string, int> map;
    string skey;
    int flag = 0;
    inout >> skey;
    key.push_back(skey);
    map[skey] = 1;
    while (!inout.eof()) {
        inout >> skey;
        for (int i = 0; i < key.size(); ++i) {
            if (key[i] == skey) {
                flag = 1;
            }
        }
        if (flag == 1) {
            map[skey]++;
        } else {
            key.push_back(skey);
            map[skey] = 1;
        }
    }
    inout.close();
    vector<PAIR> pair_vec; //用pair来实现按照pair的第二个元素大小也就是value排序
    for (auto it = map.begin(); it != map.end(); it++) {
        pair_vec.push_back(make_pair(it->first, it->second));
    }
    stable_sort(pair_vec.begin(), pair_vec.end(), cmp);
    for (auto curr = pair_vec.begin(); curr != pair_vec.end(); ++curr) {
        cout << curr->first << " " << curr->second << endl;
    }
    return 0;
}

测试用例:

Everybody knows the famous and handsome football player David Beckham, who has a happy family. For a long time, this man’s wife was known to people as David’s beautiful wife, while the fact is that Victoria works so hard for her fashion circle and she makes it. Now everyone treats her as the fashion designer.

结果:

这里写图片描述
参考:
http://www.cnblogs.com/yanchengwang/p/5988409.html
http://www.cnblogs.com/lakeone/p/5599047.html

您可能感兴趣的与本文相关的镜像

ACE-Step

ACE-Step

音乐合成
ACE-Step

ACE-Step是由中国团队阶跃星辰(StepFun)与ACE Studio联手打造的开源音乐生成模型。 它拥有3.5B参数量,支持快速高质量生成、强可控性和易于拓展的特点。 最厉害的是,它可以生成多种语言的歌曲,包括但不限于中文、英文、日文等19种语言

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值