HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Print max no of recent duplicate words

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
recentduplicatewordsprintmax

Problem

I am new to C++, learning from the book primer C++

The exercise:

Write a program to read strings from standard input looking for duplicated
words. The program should find places in the input where one word is followed
immediately by itself. Keep track of the largest number of times a single repetition
occurs and which word is repeated. Print the maximum number of duplicates, or
else print a message saying that no word was repeated.

vector words;
string w, highest_occ_word;
int occ = 1, highest_occ = 0;

while (cin >> w)
    words.push_back(w);

for (auto i = words.begin(); i != words.end(); ++i)
{
    if ((i + 1) != words.end() && *i == *(i + 1))
    {
        ++occ;
        if (highest_occ < occ)
        {
            highest_occ = occ;
            highest_occ_word = *i;
        }
    }
    else
        occ = 1;            
}

cout << highest_occ_word << " occured for " << highest_occ << " times \n";


Is this good code? If not, what can I do to improve it?

Solution

You loop from the first element to the last, and in each iteration you check if a next element exists or not. This check will only be false on the last element, it will be true for all elements before that. In other words, most of the time the check is unnecessary.

To get rid of this redundancy, you could start the iteration from the second element, and make comparisons with the previous one, which always exists. No more redundant checks.

More importantly, keep in mind that you don't need to read the entire input into memory to find the most frequent repetition. You don't need a vector. You could just parse the input word by word, always keeping only the last word in memory for comparisons. That way you will drastically reduce the memory footprint of the program.

Context

StackExchange Code Review Q#124004, answer score: 3

Revisions (0)

No revisions yet.