在加速c ++中练习3.3

时间:2014-12-21 14:57:13

标签: c++

我正在阅读“加速c ++”和“解决当前的练习3.3”这本书,其中说:

  

编写一个程序来计算每个不同单词在其输入中出现的次数。

我对此问题的解决方案是以下代码:

#include <ios>
#include <iostream>
#include <string>
#include <iomanip>
#include <algorithm>
#include <vector>


int main()
{
  std::cout << "please enter as many words as wanted" << std::endl;
  std::vector<std::string> s;
  std::string tempstring; 

  while(std::cin >> tempstring){
    s.push_back(tempstring);
    }

  std::vector<std::string> unique;
  std::vector<int> count;

  std::vector<std::string> copy = s;

  while(copy.size()>0){
    std::string search = copy[0];
    int temp = 1;
    unique.push_back(search);
    for(int i = 1;i < copy.size();++i){
      if(copy[i]==search){
    ++temp;
    copy.erase(copy.begin()+i);
      }
    }
    count.push_back(temp);
    copy.erase(copy.begin());
  }

  for(int i = 0;i<unique.size();++i){
    std::cout << unique[i] << " occurs "  << count[i] << " times" << std::endl;
  }

  return 0;
}

如果我使用输入Jo Hi Hi Jo Jo Jo me done,我会得到以下输出:

thinkstation:~c++/accelerated_code/exercises/chapter_3$ ./ex3_3 
please enter as many words as wanted
Jo Hi Hi Jo Jo Jo me done
Jo occurs 3 times
Hi occurs 2 times
Jo occurs 1 times
me occurs 1 times
done occurs 1 times

为什么不删除所有Jo?如果我只是运行

thinkstation:~c++/accelerated_code/exercises/chapter_3$ ./ex3_3 
please enter as many words as wanted
Jo Jo Hi
Jo occurs 2 times
Hi occurs 1 times

它工作正常。

1 个答案:

答案 0 :(得分:4)

在您的代码中删除重复项:

for(int i = 1;i < copy.size();++i){
  if(copy[i]==search){
    ++temp;
    copy.erase(copy.begin()+i);
  }
}

请注意,当您删除单词并因此将所有后续单词向下滑动到一个索引时,仍然会增加i,因此重复检查会跳过下一个单词。


标准库包括几种可用于实现解决方案的算法。您可以使用std::remove替换代码以检查和计算重复项:

while(copy.size()>0){
  std::string search = copy[0];

  auto new_end = std::remove(copy.begin(), copy.end(), search);
  int temp = copy.end() - new_end;
  copy.erase(new_end, copy.end());

  count.push_back(temp);
  unique.push_back(search);
}

其他一些可能对各种解决方案有所帮助的算法:std::sortstd::uniquestd::countstd::upper_bound