← index
cplusplus17.Examples/examples/word_count/word_count.cpp
Source: cplusplus17.Examples/examples/word_count/word_count.cpp
#include<iostream>
#include<string>
#include<cctype>
#include<unordered_map>
#include<vector>
#include<algorithm>
void extract_and_fill(std::istream &in, std::unordered_map<std::string, unsigned int> &words);
void sort_and_print(std::ostream &out, std::unordered_map<std::string, unsigned int> &words);
int main() {
    std::unordered_map<std::string, unsigned int> words;
    extract_and_fill(std::cin, words);
    sort_and_print(std::cout, words);
    return 0;
}
void extract_and_fill(std::istream &in, std::unordered_map<std::string, unsigned int> &words) {
    std::string token;
    bool on = true;
    while(!in.eof()) {
        if(char c = tolower(in.get()); c >= 'a' && c <= 'z') {
            if(on == true)
                token += c;
            else {
                words[token]++;
                token = "";
                token += c;
                on = true;
            }
        } else
            on = false;
    }
    if(token != "")
        words[token]++;
}
void sort_and_print(std::ostream &out, std::unordered_map<std::string, unsigned int> &words) {
    std::vector<std::string> keys;
    for(auto &i : words)
        keys.push_back(i.first);
    std::sort(keys.begin(), keys.end());
    for(auto &i : keys)
        out << i << "  " << words[i] << "\n";
}