C++Primer习题6.12

来源:互联网 发布:mysql 复合主键 编辑:程序博客网 时间:2024/05/08 11:04

题目:编写一个小程序,从标准输入读入一系列 string 对象,寻找连续重复出现的单词。程序应该找出满足以下条件的单词的输入位置:该单词的后面紧跟着再次出现自己本身。跟踪重复次数最多的单词及其重复次数。输出重复次数的最大值,若没有单词重复则输出说明信息。例如,如果输入是:

     how, now now now brown cow cow
My code:
#include<iostream>#include<string>using namespace std;int main(){    //vector<string> svec;    string preWord = "", word, maxWord;    int occurs = 0, maxOccurs = 0;     //若有重复,记录次数    while(cin >> word)    {        //第一次输入,更新preWrod        if(preWord == "")        {            preWord = word;            occurs = 1;            continue;        }//如果出现重复单词,记录加1        if(preWord == word)        {            ++occurs;        }//否则如果出现不同单词则判断,如果重复次数大于已记录的最大值,则更新最大值        else        {            if(maxOccurs < occurs)            {                maxWord = preWord;                maxOccurs = occurs;            }            //更新preword,并从头开始计数            preWord = word;            occurs = 1;        }    }    if(maxOccurs < occurs)//注意最后一次循环容易忽略    {        maxWord = word;        maxOccurs = occurs;    }    if(maxOccurs != 1 )        cout << maxWord << ": " << maxOccurs << endl;    else        cout << "There is no repetition!" << endl;    return 0;}

reference answer;

#include<iostream>#include<string>using namespace std;int main(){    string preWord, currWord;       //当前输入的单词及前一次单词    string repWord;                 //重复次数最多的单词    //当前单词的重复次数及单词重复的次数最大值    int currCnt = 0, maxCnt = 1;    cout << "Enter some words(Ctr+Z to end): "<< endl;    while(cin >> currWord)    {        if(currWord == preWord)     //当前单词重复出现            ++currCnt;        else //出现新单词        {            if(currCnt > maxCnt)//出现了重复次数更多的单词,更新4            {                maxCnt = currCnt;                repWord = preWord;            }            currCnt = 1;        }        preWord = currWord;    }    if(currCnt > maxCnt)    {        maxCnt = currCnt;        repWord = preWord;    }    if(maxCnt != 1)        cout << '"' << repWord << '"' << " repeated for " << maxCnt << " times!" << endl;    else        cout << "There is no repeated word." << endl;    return 0;}