我需要計算唯一字的數量,並使用下面的代碼,它似乎沒有正確計算。我不知道我還能做些什麼才能使它工作,並真的很感激任何建議。我在查找獨特單詞時遇到問題,如何改進代碼?
#include <iostream>
#include <string>
#include <set>
using std::string;
using std::set;
unsigned long countUWords(const string& s)
{
set<string> uw;
string word = "";
for(size_t i = 0; i < s.size(); i++){
bool words = (s[i] >= 'a' && s[i] <= 'z') || (s[i] >= 'A' && s[i] <= 'Z');
if(words){
word += s[i];
}
else if(!words && word != ""){
uw.insert(word);
word = "";
}
}
if (word != "")
uw.insert(word);
return uw.size();
}
int main()
{
string s;
unsigned long UWords = 0;
while(getline(cin, s)){
UWords += countUWords(s);
}
cout << UWords << endl;
return 0;
}
將所有單詞放在字典中,其中的值是出現次數。完成後,唯一的是每個出現一次的那些。 – Renan
它在哪裏失敗? –
當你說「獨特」時,你的意思是「獨特」還是「僅出現一次」? – jwismar