计算字符串向量中单词的出现次数
Counting occurrences of words in a string vector
我正在尝试创建一个字典,将文件读取为字符串向量,并计算每个唯一单词出现的次数。以下是目前为止的内容:
int main()
{
ifstream input1;
input1.open("Base_text.txt");
vector<string> base_file;
vector<int> base_count;
if (input1.fail())
{
cout<<"Input file 1 opening failed."<<endl;
exit(1);
}
make_dictionary(input1, base_file, base_count);
}
void make_dictionary(istream& file, vector<string>& words, vector<int>& count)
{
string word;
int i=0;
while (file>>word)
{
words.push_back(word);
cout<<words[i];
i++;
}
for (i=0; i<words.size(); i++)
{
if ((words[i+1]!=words[i]))
{
count.push_back(i);
}
}
问题1:如何让向量包含空格并识别单个单词?问题2:对于如何继续第二部分(for循环)有什么想法吗?
这是相当低效的。你应该使用
std::map<string, int>
。这既容易又有效。
遍历文件。当你看到一个单词时,看看它是否在地图上。如果不是,则添加一个计数为1的新单词。
相关文章:
- 从字符串变量中逐字符读取单词
- 使用std::mt19937从字符串中返回一个随机单词
- C++-字符串是否包含一个带有简单循环的单词
- 在C++中查找(奇怪的)字符串中的单词
- 当字符串是某个单词时给出输出?
- 替换字符串中的单词,但忽略引号中的单词
- 替换字符串位置 X 中的单词C++
- 视觉C++使用 map 来比较字符串中的每个单词
- 给定一个单词数组和一个字符串,如何计算给定字符串中的所有单词
- 输出返回编号。等于输入字符串的单词的字符串数
- 在字符串的每个单词的末尾插入字符串
- 分析字符串中的双精度和单词
- 如何使用运算符>>在自定义字符串中输入多个单词?
- 反转字符串中单词的位置,而不更改 O(1) 空格限制中特殊字符的顺序
- 使用正则表达式c++从单词和分隔符之间的字符串中提取所有子字符串
- 从文件 (C++) 输入两个单词字符串
- 在一行中输入具有其他输入类型的多个单词字符串
- 打印以 "a" 开头的单词(字符串中)
- 如何让我的代码以不会切断单词(字符串)的方式运行?
- 句子变成单词c++字符串