#include <iostream>
#include <string>
#include <sstream>
#include <map>
int main()
{
std::string input;
std::cout << "Enter input: ";
std::getline(std::cin, input);
std::map<std::string, int> m;
std::map<std::string, int>::iterator it;
std::istringstream iss(input);
std::string words;
do {
iss >> words;
it = m.find(words);
if(it != m.end())
{
m.insert(it, std::pair<std::string, int>(words, m[words] + 1));
}
else
{
m.insert(std::pair<std::string, int>(words, 1));
}
}while(iss);
for(std::map<std::string, int>::iterator it = m.begin(); it != m.end(); ++it)
{
std::cout << it->first << " - " << it->second << std::endl;
}
return 0;
}
問題是,即使出現兩次,它也會爲每個單詞打印1個字。可能是什麼問題呢?我不確定我的迭代器測試是否爲空是正確的。計算每個不同單詞出現在其輸入中的次數C++
http://stackoverflow.com/questions/4888879/elegant-ways-to-count-the-frequency-of-words-in-a-file – 2011-03-19 18:17:24
您還可以在這裏看到其他解決方案:[優雅的方法來計算文件中的單詞頻率](http://stackoverflow.com/questions/4888879/elegant-ways-to-count-the-frequency-of-文字中的文字) – Nawaz 2011-03-19 18:33:38