例:

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

算法实现:

#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

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐