typestar

word_freq.cpp in C++

A word-frequency report over an inline passage, one std::map doing the counting.

#include <algorithm>
#include <cctype>
#include <format>
#include <iostream>
#include <map>
#include <string>
#include <vector>

// word_freq: count word occurrences in an inline passage

int main() {
    const std::string text =
        "The quick brown fox jumps over the lazy dog. "
        "The dog barks; the fox runs. Quick thinking, that fox.";

    std::map<std::string, int> freq;
    int total = 0;
    std::string word;
    for (char raw : text + " ") {
        unsigned char c = static_cast<unsigned char>(raw);
        if (std::isalpha(c)) {
            word += static_cast<char>(std::tolower(c));
        } else if (!word.empty()) {
            ++freq[word];
            ++total;
            word.clear();
        }
    }

    std::cout << "words total: " << total << "\n";
    std::cout << "words unique: " << freq.size() << "\n";

    std::vector<std::pair<std::string, int>> ranked(freq.begin(),
                                                    freq.end());
    std::ranges::sort(ranked, [](const auto &a, const auto &b) {
        if (a.second != b.second) return a.second > b.second;
        return a.first < b.first;
    });

    std::cout << "top 5:\n";
    for (std::size_t i = 0; i < ranked.size() && i < 5; ++i) {
        std::cout << std::format("  {:<8} {}\n",
                                 ranked[i].first, ranked[i].second);
    }

    std::cout << "seen once:";
    for (const auto &[entry, count] : ranked) {
        if (count == 1) {
            std::cout << " " << entry;
        }
    }
    std::cout << "\n";
}

How it works

  1. A character walk lowercases letters into word and flushes it into freq at each break.
  2. Copying the map into a vector lets std::ranges::sort rank by count, then alphabetically.
  3. The top-5 loop prints aligned rows with std::format; a final pass lists words seen once.

Keywords and builtins used here

The run, in numbers

Lines
53
Characters to type
1244
Tokens
406
Three-star pace
80 tpm

At the three-star pace of 80 tokens a minute, this run takes about 304 seconds.

Type this snippet

Step 1 of 3 in Encore, step 25 of 27 in Language basics.

← Previous Next →