首页 > 解决方案 > 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;
  }
}

所以我的问题是,有没有办法做上述但使用数组而不是映射?

标签: c++arraysdictionarycount

解决方案


由于禁止使用地图,因此一个好的解决方案就是使用两个向量,一个用于单词,另一个用于每个单词的出现次数,并具有匹配的索引。

归根结底,它的工作原理与地图非常相似,但是由于您具有任意限制,因此可以选择。

要实现这一点,只需用M两个向量替换,我们称它们为wordVectorcountVector。然后,您可以插入这样的单词以确保索引匹配并且计数良好:

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 = "";
      }
    }

推荐阅读