【问题标题】:c++ count the number of occurrences of each word in string using an array?c ++使用数组计算字符串中每个单词的出现次数?
【发布时间】:2020-08-31 04:57:48
【问题描述】:

我目前有一个函数可以执行问题所说的(计算字符串中每个单词的出现次数)但是它使用 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;
  }
}

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

【问题讨论】:

  • 当然,要计数的单词映射只是两个数组:在数组中搜索单词,然后在找到它的位置获取索引,并在计数数组上使用该索引。
  • 请注意,您的基于map 的解决方案效率非常低且不必要地复杂。可以大大简化:void wordCount(const std::string &amp;wordFile) { std::map&lt;std::string, int&gt; M; std::istringstream iss(wordFile); std::string word; while (iss &gt;&gt; word) { M[word]++; } for (const auto &amp;it : M) { std::cout &lt;&lt; it.first &lt;&lt; ": Occurs " &lt;&lt; it.second &lt;&lt; std::endl; } }
  • This is for a university level task and we arent allowed to use maps for the count。我把它读成This is for a university level task and we arent allowed to use screwdrivers to loosen the screws

标签: c++ arrays dictionary count


【解决方案1】:

是的,可以做到,但也可以,您通常希望以不同的方式(好吧,完全)来做。

我会分阶段进行:

  1. 将输入字符串分解为单词并创建单个单词的向量
  • 并可能进行一些按摩,例如将全部转换为小写
  1. 对单词向量进行排序
  2. 从列表中的第一个单词开始,统计后面相同单词的个数
  • 并将 {word:count} 结果添加到您的输出中
  1. 从与其前任不匹配的第一个单词开始重复此操作

  2. (作为奖励)按计数(可能按降序排列)对 {word:count} 对的向量进行排序,因此您会得到如下计数:

     the: 583
     a: 428
     an: 422
     // ...
     dioxide: 2
     arthurian: 1
    

【讨论】:

    【解决方案2】:

    一个很好的解决方案是使用两个向量,一个用于单词,另一个用于每个单词的出现次数,并具有匹配的索引。

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

    要实现这一点,只需将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 = "";
          }
        }
    

    【讨论】:

      猜你喜欢
      • 2011-11-26
      • 2017-09-04
      • 1970-01-01
      • 2016-06-28
      • 2021-04-19
      • 1970-01-01
      • 2015-09-14
      • 1970-01-01
      相关资源
      最近更新 更多