Re: Function to output words in a vector and the occurrence.
On 20 Apr, 01:32, Xernoth <JonH.Pe...@googlemail.com> wrote:
Hi,
I have an exercise that requests the following:
Write a function that reads words from an input stream and stores them
in a vector.
Use that function both to write programs that count the number of
words in the input,
and to count how many times each word occurred.
The below code works fine, but would like some advice on the
occurrence count.
I have commented out the part that concerns me.
#include <iostream>
#include <vector>
#include <string>
using std::cin;
using std::cout;
using std::endl;
using std::istream;
using std::string;
using std::vector;
istream& read(istream& in, vector<string>& words)
{
if (in)
{
words.clear();
string temp;
while (in >> temp)
words.push_back(temp);
in.clear();
}
return in;
}
int main()
{
cout << "Enter a list of words:" << endl;
vector<string> words;
read(cin, words);
vector<string>::size_type vecSize = words.size();
cout << "You entered " << vecSize << " words." << endl;
for (vector<string>::size_type i = 0; i < vecSize; i++)
{
int wordCount = 0;
for (vector<string>::size_type j = 0; j < vecSize; j++)
{
if (words[i] == words[j])
{
wordCount += 1;
//if (wordCount > 1)
//{
// words.erase(words.begin() + j);
// vecSize = words.size();
//}
}
}
cout << "The word: " << words[i] << " occured " << wordCount
<< " times." << endl;
}
return 0;
}
With that portion of code commented, let's say I have an input with
the words:
"This that then that"
My output will appear as:
You entered 4 words.
The word: this occured 1 times.
The word: that occured 2 times.
The word: then occured 1 times.
The word: that occured 2 times.
With the code uncommented, the output appears as:
You entered 4 words.
The word: this occured 1 times.
The word: that occured 2 times.
The word: then occured 1 times.
Which is what I am after, but is commented code a poor method to
achieve this effect?
I'm not sure how much better it it but it would reduce the code to a
single loop if you first sorted the vector (using std::sort()) and
then went through the vector and took notice of when the word changed,
something like this (totally untested):
cout << "You entered " << vecSize << " words." << endl;
sort(words.begin(), words.end())
string currentWord = words[0];
int wordCount = 0;
for (vector<string>::size_type i = 0; i < vecSize; i++)
{
if (words[i] == currentWord)
++wordCount;
else
{
cout << "The word: " << currentWord << " occured " << wordCount <<
" times\n";
wordCount = 1;
currentWord = words[i];
}
}
--
Erik Wikstr=F6m