2014-03-28 51 views
-1
WordCount countWords(const QString &file) 
    { 
     QFile f(file); 
     f.open(QIODevice::ReadOnly); 
     QTextStream textStream(&f); 
     WordCount wordCount; 

     while (textStream.atEnd() == false) 
      foreach (QString word, textStream.readLine().split(" ")) 
       wordCount[word] += 1; 

     return wordCount; 
    } 

... 

QStringList files = findFiles("../../", QStringList() << "*.cpp" << "*.h"); 

... 

int mapReduceTime = 0; 
{ 
    QTime time; 
    time.start(); 
    WordCount total = mappedReduced(files, countWords, reduce); 
    mapReduceTime = time.elapsed(); 
    qDebug() << "MapReduce" << mapReduceTime; 
} 

說我想跟蹤我正在處理哪個文件,我可以創建一個全局靜態變量,並在每次啓動運行時遞增它,在countWord函數內部知道我正在做一些處理在檔案號碼1?或者是不可能知道哪些文件將被首先處理?我問,因爲mapreduce允許並行處理,但我不知道操作系統將如何安排線程。Qt庫中的mapreduce是否保留了輸入文件的序列?

+0

您確實需要發佈完整的代碼,以表明您正在嘗試做什麼,並說明如何實現您的目標。 –

回答

0

因爲每個映射操作通常需要不同的時間,所以不可能精確地知道處理運行的順序。

一個簡單的解決方案是不處理原始文件列表,而是處理(索引,文件名)對列表。

您還應該跳過空字符串,並至少處理打開給定文件以供閱讀的失敗。寫作boolExpr == false的地道方式簡直就是! boolExpr

typedef QPair<int, QString> FileEntry; 

WordCount countWords(const FileEntry &entry) 
{ 
    WordCount wordCount; 
    QFile f(entry.second); 
    if (!f.open(QIODevice::ReadOnly)) return wordCount; 
    QTextStream ts(&f); 

    while (!ts()) 
     foreach (QString word, ts().split(" ", QString::SkipEmptyParts)) 
     wordCount[word] ++; 

    return wordCount; 
} 

QStringList f = findFiles("../../", QStringList() << "*.cpp" << "*.h"); 
QList<FileEntry> fileEntries; 
fileEntries.reserve(f.size()); 
int i = 0; 
foreach (QString file, f) 
    fileEntries << qMakePair(i++, file); 
mappedReduced(fileEntries, countWords, reduce); 
+0

假設你有一個2d數組,並且你將每行傳遞給mapreduce – user3435009

+0

好吧,我沒有看到編輯。爲什麼你會使用元組而不是QPair? – user3435009

+0

把所有東西放在一起,你會怎麼做? – user3435009

相關問題