3-3. 编写一个程序来计算每个不同单词在其输入中出现的次数
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;
}
我不确定 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);
}
}
上面的代码还表明,您应该只插入重复的单词。 无需输入所有单词,然后进行处理。
相关文章:
- 3-3. 编写一个程序来计算每个不同单词在其输入中出现的次数
- 输出返回编号。等于输入字符串的单词的字符串数
- 如何使用运算符>>在自定义字符串中输入多个单词?
- 在C++中使用哪个函数来输入多个单词,比如C中的fgets
- 输入一个字符串并将其除以单词
- 如何在函数中输入数字以输出单词?
- C++:如果用户输入数字将其转换为单词,并且如果按回车键程序应退出,则使用开关大小写
- 如何输入每个单词在字符串数组中的句子,直到用户按Enter键
- 从文件 (C++) 输入两个单词字符串
- 在一行中输入具有其他输入类型的多个单词字符串
- 如何识别输入的输入字符串在 c++ 中是两个还是多个单词
- 如何将文件复制到另一个文件中,但是用用户输入的单词替换单词
- 如何从包含多个句子的输入文件中表达单个单词.C
- 从输入的句子中构建单词列表
- 根据输入文本对单词进行排序,具体取决于重复多少次
- C 输入多个单词要字符串
- 用输入中给出的单词填充字符串
- 我如何修改我的C 程序以显示用户输入的单词,并使用堆栈向后
- 需要帮助C++计算器输入单词
- c++在二叉搜索树中从文本文件中输入单词