このページでは

文字数

Map-Reduceアルゴリズムの使用方法を示します。

Qt Concurrent の「Word Count」サンプルは、一連のファイル内の単語数をカウントするという問題にMapReduceアルゴリズムを適用した例を示しています。

まず、アプリケーションは QFileDialog を起動して開始パスを選択し、その後、出力をコンソールに出力します。

例の動作

このサンプルは、以下の手順で実行できます。

操作の比較

テキストファイル内の単語数をカウントする際、単一スレッドの逐次処理と、mappedReduce() を使用したマルチスレッド処理を比較します。

    ...
    WordCount total = singleThreadedWordCount(files);
    ...
    WordCount total = QtConcurrent::mappedReduced(files, countWords, reduce).result();
    ...

mappedReduced 関数の最初の引数は、操作対象となるコンテナです。2番目の引数は、countWords() であるマッピング関数です。これは複数のスレッドによって並列に呼び出されます。3番目の引数は、reduce() であるリダクション関数です。これは、マッピング関数が返す結果ごとに1回呼び出され、最終的な計算結果を生成します。

この関数は、型が `WordCount` の `QFuture ` オブジェクトを返します。この `QFuture ` に対して直ちに `result ` 関数を呼び出し、結果が得られるまでそれ以降の実行をブロックします。

注:マッピング関数は 複数のスレッドから呼び出されるため、スレッドセーフである必要があります。

サンプルプロジェクト @ code.qt.io

© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.