view wordcount.cc @ 23:c3fb5f666e2d

graphs: Two graph algorithms
author Lewin Bormann <lbo@spheniscida.de>
date Sun, 09 Apr 2023 17:17:04 +0200
parents ecc574aa2021
children
line wrap: on
line source


#include "lib/exec.h"

#include <algorithm>
#include <numeric>
#include <iterator>
#include <iostream>
#include <memory>
#include <string>
#include <unordered_map>

using namespace std;

unordered_map<string, unsigned int> word_count(istream& is) {
    istream_iterator<string> iter(is);
    unordered_map<string, unsigned int> counts;

    auto reducer = [](decltype(counts)* c, string word) -> decltype(counts)* {
        auto entry = c->find(word);
        if (entry != c->end()) {
            entry->second++;
        } else {
            c->insert(make_pair(move(word), 1));
        }

        return c;
    };
    auto mapper = [](const string& w) -> const string& { return w; };

    transform_reduce(iter, decltype(iter)(), &counts, reducer, mapper);

    return counts;
}

template<typename K, typename V>
void format_word_count(const unordered_map<K, V>& counts) {
    vector<pair<K,V>> pairs(counts.cbegin(), counts.cend());
    sort(pairs.begin(), pairs.end(), [](const pair<K,V>& p1, const pair<K,V>& p2) -> bool { return p1.second < p2.second; });

    for_each(pairs.begin(), pairs.end(), [](const pair<K,V>& p) {
            fmt::print("{} -> {}\n", p.first, p.second);
    });
}

int main(int argc, char** argv) {
    if (argc < 2) {
        timeit_f([]() {
                format_word_count(word_count(cin));
                }, "wordcount");
    }

    return 0;
}