c++ - c ++使用数组计算字符串中每个单词的出现次数?
问题描述
我目前有一个函数可以执行问题所说的(计算字符串中每个单词的出现次数)但是它使用 map。这是针对大学级别的任务,我们不允许使用地图进行计数(我没看过哈哈)
void wordCount(std::string wordFile)
{
std::map<std::string, int> M;
std::string word = "";
for (int i = 0; i < str.size(); i++)
{
if (str[i] == ' ')
{
if (M.find(word) == M.end())
{
M.insert(make_pair(word, 1));
word = "";
}
else
{
M[word]++;
word = "";
}
}
else
word += str[i];
}
if (M.find(word) == M.end())
M.insert(make_pair(word, 1));
else
M[word]++;
for (auto &it : M)
{
std::cout << it.first << ": Occurs "
<< it.second
<< std::endl;
}
}
所以我的问题是,有没有办法做上述但使用数组而不是映射?
解决方案
由于禁止使用地图,因此一个好的解决方案就是使用两个向量,一个用于单词,另一个用于每个单词的出现次数,并具有匹配的索引。
归根结底,它的工作原理与地图非常相似,但是由于您具有任意限制,因此可以选择。
要实现这一点,只需用M
两个向量替换,我们称它们为wordVector
和countVector
。然后,您可以插入这样的单词以确保索引匹配并且计数良好:
if (str[i] == ' ')
{
if (wordVector.find(word) == wordVector.end())
{
wordVector.insert(word);
countVector.insert(1);
word = "";
}
else
{
int index = wordVector.find(word)
++countVector[index];
word = "";
}
}
推荐阅读
- javascript - react javascript - json如何将多个数组元素合并为一个字符串
- sql - 将 SQL SELECT 结果列为列名和值对
- python - 在 Python 3.x 中解码邮件主题 Thunderbird
- reactjs - 在 React Native 中向状态数组添加数据
- canvas - 无法让滚动条在 Tkinter 中用于画布
- javascript - 未捕获的 TypeError:p.addEventListener 不是函数,我该如何解决?
- hive - LIKE 运算符是否仍然利用 Hive 中的分桶?
- python - 抓取 Pandas 列 Python 的方法
- java - 如何让 ServletFilter 处理嵌入式 Jetty 中的欢迎文件?
- excel - 如何创建一个“汇总”单元格,聚合列中的唯一值?