2010-09-29 24 views
2

我正在練習從加速C++:計數每個不同的字有多少次出現在輸入

寫一個程序來計算每個不同的字有多少次出現在其輸入。

這裏是我的代碼:

#include <iostream> 
#include <string> 
#include <vector> 

int main() 
{ 
    // Ask for 
    // and read the input words 
    std::cout << "Please input your words: " << std::endl; 
    std::vector<std::string> word_input; 
    std::string word; 
    int count = 0; 
    while (std::cin >> word) 
    { 
     word_input.push_back(word); 
     ++count; 
    } 

    // Compare the input words 
    // and output the times of every word compared only with all the words 

    /***** I think this loop is causing the problem ******/ 
    for (int i = 0; i != count; ++i) 
    { 
     int time = 0; 
     for (int j = 0; j != count; ++j) 
     { 
      if (word_input[i] == word_input[j]) 
       ++time; 
      else 
       break; 
     } 

     std::cout << "The time of " 
        << word_input[i] 
        << " is: " 
        << time 
        << std::endl; 
    } 

    return 0; 
} 

如果你編譯並運行這個程序,你會看到:

Please input your words:

我輸入如下:

 
good good is good 
EOF 

然後它顯示:

 
The time of good is: 2 
The time of good is: 2 
The time of is is: 0 
The time of good is: 2 

我預期的結果是:

 
The time of good is: 3 
The time of is is: 1 

我不想使用地圖,因爲我還沒有得知呢。

是什麼導致了這種意外的行爲,我該如何解決?

回答

3

假設的std ::向量是你在這一點認識的唯一的容器,而你還沒有得到到std ::對呢,我建議如下:

  • 添加a std::vector<int> word_count
  • 在您的std::cin while循環中,您檢查當前單詞是否存在於word_input中。如果不是,你push_back這個詞和push_back一個在word_count。如果在word_input的某個索引i處已經有當前單詞的條目,則您在此索引i處增加word_count。因此,您輸入的每個不同的單詞只出現一次word_input中,輸入的次數在word_count中管理。
  • 輸出,並行步進word_inputword_count並輸出每個單詞的字數。

完成。

但這一切都變得更簡單,更優雅與std::map。繼續閱讀! :-)

1

只要刪除else語句即可。

int main() 
{ 
    // Ask for 
    // and read the input words 
    std::cout << "Please input your words: " 
       << std::endl; 
    std::vector<std::string> word_input; 
    std::string word; 
    int count = 0; 
    while (std::cin >> word) 
     { 
      word_input.push_back(word); 
      ++count; 
     } 

    // Compare the input words 
    // and output the times of every word compared only with all the words 
    for (int i = 0; i != count; ++i) 
     { 
      int time = 0; 
      for (int j = 0; j != count; ++j) 
       { 
        if (word_input[i] == word_input[j]) 
         ++time; 
        // else   <========== You don't need this! 
        // break; 
       } 

      std::cout << "The time of " 
       << word_input[i] 
       << " is: " 
       << time 
       << std::endl; 
     } 

    return 0; 
} 

請注意,對於較大的輸入,您的解決方案非常慢。更好的主意是爲你的'詞典'使用散列表(std :: map)或者排序那個向量並且計算不同的單詞(在O(logN * N)中運行,你的解決方案是O(N^2))。

+0

std :: map沒有作爲散列表實現,因此它仍然很慢。請參閱stdext :: hash_map或更新的std :: tr1 :: unordered_map。 – 2010-09-29 11:21:33

+0

我不想使用地圖,因爲我沒有學到〜我剛學了3章。我曾經編輯過我的問題。也許你沒有得到我想要的。謝謝你們一樣〜 – Darson 2010-09-29 11:23:32

+0

@Mark Ingram:或者'boost :: unordered_map'適合較老的編譯器。 – lunaryorn 2010-09-29 11:27:47

相關問題