[英]Write a program to count how many times each distinct word appears in its input
[英]3-3. Write a program to count how many times each distinct word appears in its input
在這:
#include <iostream>
#include <string>
#include <vector>
using std::cout; using std::cin; using std::vector; using std::endl;
using std::string;
int main(){
cout << "enter strings: " << endl;
string s;
vector<string> in;
vector<string> out;
vector<int> count;
while(cin >> s)
in.push_back(s);
out.push_back(in[0]);
count.push_back(1);
int index = 0;
for(int i=0;i<in.size();i++){
if(out[index]==in[i])
(count[index])++;
else{
out.push_back(in[i]);
count.push_back(1);
index++;
}
}
cout << endl;
for(int i=0;i<count.size();i++)
cout << "i: " << i << "\tval: " << count[i] << endl;
}
我不確定使變量index
僅在count
向量中向前移動以僅計算那些已經出現的單詞。 有人可以幫忙嗎? 書中的練習Accelerated C++ Practical Programming by Example
如果您不能使用std::map
,您可以將單詞與頻率相關聯:
struct Info
{
std::string word;
int frequency;
};
//...
std::vector<Info> database;
//...
std::string word;
while (std::cin >> word)
{
// Find the word:
const size_t length = database.size();
for (unsigned int i = 0; i < length; ++i)
{
if (database[i].word == word)
{
database[i].frequency++;
break;
}
}
if (i >= length)
{
Info new_info{word, 0};
database.push_back(new_info);
}
}
上面的代碼還表明您應該只插入重復的單詞。 無需輸入所有單詞,然后進行處理。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.