Menu
Coddy logo textTech

復習 - 単語の頻度

CoddyのC++ジャーニー「オブジェクト指向プログラミング」セクションの一部。レッスン 75/104。

challenge icon

チャレンジ

簡単

頻度順に並べ替えた単語数を処理して表示する、単語頻度アナライザーを作りましょう。これは、学習したすべての STL コンポーネントを組み合わせた典型的なテキスト処理タスクです。カウントには map、並べ替えには vector、走査にはイテレーター、カスタム並べ替えロジックにはラムダを使用します。

コードを 2 つのファイルに分けて構成します。

  • WordAnalyzer.h: 単語のカウントと分析を管理する WordAnalyzer クラスを定義します。

    クラス内部では、単語のカウントを格納するために std::map<std::string, int> を使用します。次のメソッドを Implement してください。

    • addWord(const std::string& word): given word のカウントを Increments します
    • getCount(const std::string& word): 特定の単語のカウントを Returns します(found でない場合は 0)
    • getTotalWords(): add された単語の合計数(すべての counts の合計)を Returns します
    • getUniqueWords(): unique な単語の数(map のサイズ)を Returns します
    • printByFrequency(): すべての単語を frequency の descending order で並べ替えて Prints します。同じ frequency の単語については、alphabetically に sort します。各行には word: count を表示します

    printByFrequency() では、map の contents を pairs の vector に移し、その後、まず count(descending)、同じ場合は word(ascending)で比較する lambda とともに std::sort を使用します。

  • main.cpp: 1 行目で、後に続く単語の数を示す整数 n を Read します。その後、n 個の単語を 1 行に 1 つずつ Read します。

    WordAnalyzer を作成し、すべての単語を add した後、次を表示します。

    1. Total words: <count> を Print します
    2. Unique words: <count> を Print します
    3. Word frequencies: を Print し、その後 printByFrequency() を呼び出します

たとえば、次の入力の場合:

7
apple
banana
apple
cherry
banana
apple
date

出力は次のようになります。

Total words: 7
Unique words: 4
Word frequencies:
apple: 3
banana: 2
cherry: 1
date: 1

apple が最初(frequency が最も高い)に表示され、続いて banana が表示され、その後、cherrydate は count が同じため alphabetically に並べ替えられていることに注目してください。

別の例として、次の入力の場合:

5
the
cat
the
sat
the

出力:

Total words: 5
Unique words: 3
Word frequencies:
the: 3
cat: 1
sat: 1

自分で試してみよう

#include <iostream>
#include <string>
#include "WordAnalyzer.h"

using namespace std;

int main() {
    int n;
    cin >> n;
    
    WordAnalyzer analyzer;
    
    // TODO: n個の単語を読み取り、analyzerに追加する
    
    // TODO: "Total words: <count>" を出力する
    
    // TODO: "Unique words: <count>" を出力する
    
    // TODO: Print "Word frequencies:" and call printByFrequency()
    
    return 0;
}

オブジェクト指向プログラミングのすべてのレッスン

自分で練習してみよう: C++オンラインコンパイラ