3-3. 编写一个程序来计算每个不同单词在其输入中出现的次数

3-3. Write a program to count how many times each distinct word appears in its input

本文关键字:输入 单词 一个 计算 程序      更新时间:2023-10-16

在此:

#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;
}

我不确定 hot 使变量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);
}
}

上面的代码还表明,您应该只插入重复的单词。 无需输入所有单词,然后进行处理。