C++primer第五版 练习5.14

来源:互联网 发布:淘宝怎么投诉盗用图片 编辑:程序博客网 时间:2024/05/19 20:42

统计连续出现的单词及其出现的最大次数

这道练习使可以参考本书第一章那个 例题的
但统计最大次数,出现最多的单词。
就需要自己去补充啦

创建整型变量cnt用来计数,temp表示临时值,max存放最大值

还用了exit(0)来实现函数直接终止。。

失误啊,阅读别的答主的答案之前未考虑到输入的字符串中有重复次数一样的

终板程序已修正上述问题

终版程序

#include<iostream>#include<vector>#include<string>#include<cstdlib>using namespace std;int main(){    string i_before,i_after;    vector<string> v(1000);    //设置为1000 容纳重复的单词          int max=1,cnt2=0,cnt=1,k=0;  //这组数设置的很巧妙 ,结合if语句阅读              if(cin>>i_before)    {             while(cin>>i_after)              {                                           if(i_after==i_before)                ++cnt;             else                                 {               i_before=i_after;              cnt=1;            }                                       //基础的输入模块            if(cnt>=max)                //判断模块               {                                          if(cnt>max)            //一旦发现当前重复的单词次数超过之前的次数最大值,                {  int k=0;            // 立马重新擦写vector                    cnt2=max=cnt;                                                v[k]=i_after;                   for(int j=k+1;j!=v.size();++j)                             v[j]="";                }                   else                {                    if(cnt2==max)       //确保个个都不同的单词不会被写入,同时次数相同的一定写入                   {                          v[++k]=i_after;                       }                }           }           }                                       if(max==1)                     //每个都不同,就是最大值一直都是一            {            cout<<"任何单词都没有连续出现过"<<endl;            exit(0);                                          }            for(auto it=v.begin();it!=v.end();++it)            {              if(*it!="")                 //输出vector元素                 cout<<"单词 "<<*it<<" 连续出现了 "<<cnt2<<" 次 "<<endl;           }    }    return 0;} 

原始程序 存在上述问题

字符串i为第一次输入后作为每次与新输入比较的对象
字符串j用作每次新输入
t用来存最大的单词。

#include<iostream>#include<vector>#include<string>#include<cstdlib>using namespace std;int main(){    string i,j,t;    int cnt=1,max=0,temp=0;    if(cin>>i)    {      while(cin>>j)      {        if(i==j)        {          ++cnt;        }        else        {          i=j;         cnt=1;        }        temp=cnt;        if(temp>max)        {           max=temp;           t=j;        }      }        if(max==1)        {         cout<<"任何单词都没有连续出现过"<<endl;         exit(0);           }       cout<<"单词 "<<t<<" 连续出现了 "<<max<<" 次 "<<endl;    }    return 0;}