2012-03-22 26 views
0

加速C++中的練習3-3讓我對循環設計有兩個更廣泛的問題。練習的挑戰是將任意數量的單詞讀入矢量,然後輸出給定單詞在該輸入中出現的次數。我已經包含下面我相關代碼:循環設計:計數和隨後的代碼複製

string currentWord = words[0]; 
words_sz currentWordCount = 1; 
// invariant: we have counted i of the current words in the vector 
for (words_sz i = 1; i < size; ++i) { 
    if (currentWord != words[i]) { 
     cout << currentWord << ": " << currentWordCount << endl; 
     currentWord = words[i]; 
     currentWordCount = 0; 
    } 
    ++currentWordCount; 
} 
cout << currentWord << ": " << currentWordCount << endl; 

注意輸出代碼必須循環處理的最後一個字之外再出現。我意識到我可以將它移動到一個函數,如果我擔心重複代碼的複雜性,只需調用函數兩次。

問題1:這種解決方法是常見的嗎?有沒有一種典型的方法來重構循環以避免這種重複?

問題2:儘管我的解決方案非常簡單,但我習慣於從零開始計算。有沒有一種更可接受的方式來編寫這個循環?或者這是最佳實施?

+0

'std :: map word_count; for(const std :: string&word:words){word_count [word] ++; } for(std :: pair count:word_count){std :: cout << count.first <<「:」<< count.second <<「\ n」; }'。或者其他的東西。 – 2012-03-22 04:39:12

+0

代碼被破壞,或者您的問題描述已關閉。你在這裏計算連續出現的次數,因爲'[「cat」,「dog」,「cat」]'會輸出:'cat:1','dog:1','cat:1'。 – 2012-03-22 07:58:36

回答

0

爲什麼你不能使用地圖http://www.cplusplus.com/reference/stl/map/與字作爲鍵和值作爲計數?

+0

OP代碼是O(1)在空間(baring初始輸入),你的解決方案不是......因爲你沒有解決同樣的問題。 – 2012-03-22 07:59:33