Iterate over the stream:
There is an iterator that acts on a stream (treating the stream like a container). So you don't need to read the data into a container and then parse the container.
Replace:
while (cin >> w)
words.push_back(w);
for (auto i = words.begin(); i != words.end(); ++i)
{
// STUFF
}
With:
using WordIter = std::istream_iterator<std::string>;
for(auto i = WordIter(std::cin); i != WordIter(); ++i)
{
// STUFF
}
One Variable Per Line:
Declare only one variable per line:
string w, highest_occ_word;
int occ = 1, highest_occ = 0;
Also declare variables as close to the point of first use as you can there is no point in declaring them all at the top. This has a couple of advantages. 1) You can see the type. 2) There constructors are not called if you never get to the point of declaration. 3) It makes the code more logical and less cluttered (PO).
Prefer look back
Not sure I like your look forward approach.
for (auto i = words.begin(); i != words.end(); ++i)
{
if ((i + 1) != words.end() && *i == *(i + 1))
I would use the current iterator with state I had saved from the previous iteration.
std::string wordOfLongestSeq;
std::size_t countOfLongestSeq = 1; // have to beat 1.
std::string currentWord;
std::size_t courrentLength;
using WordIter = std::istream_iterator<std::string>;
for(auto loop = WordIter(std::cin); loop != WordIter(); ++loop)
{
std::string const& word = *loop;
// If the new word does not match the current word.
// This works for the first word (as current word is "")
if (word != currentWord) {
// We are switching words.
// But before we do check to see if it broke
// the previous record.
if (courrentLength > countOfLongestSeq) {
countOfLongestSeq = courrentLength;
wordOfLongestSeq = currentWord;
}
// Reset the current word.
currentWord = word;
courrentLength = 0;
}
// Increment the count of words.
++courrentLength;
}
// Check to see if the last word
// broke the record.
if (courrentLength > countOfLongestSeq) {
countOfLongestSeq = courrentLength;
wordOfLongestSeq = currentWord;
}
Check your requirements:
Print the maximum number of duplicates, or else print a message saying that no word was repeated
Looks like you don't need fulfill the else portion from the requirements.
cout << highest_occ_word << " occured for " << highest_occ << " times \n";