first of all this is my first question on the site. I've done a lot of research and I don't think I found quite a specific issue as this, but if I'm wrong, feel free to correct me in an answer and link said topic to me.
Onto the problem itself, the assignment consists of a console application that will display each distinct word entered to it, as well as the number of occurrences for each unique word. I decided that the way to solve this would be through the use of a vector<string>
and then use a nested loop structure where the outer loop would represent each unique word, and where the inner loop would be used to compare the word from the outer loop to each existing word in the vector.
However. I've ran across a problem.
With this basic setup:
//Sort vector into alphabetical order
sort(words.begin(), words.end()); //this only sorts them alphabetically, but equal strings are "next" to each other
//Find unique values
for(string::size_type i=0; i != words.size(); i++) {
int count = 0;
for(string::size_type j=0; j != words.size(); j++) {
if(words[i] == words[j]){
count++;
}
}
cout << words[i] << " appeared: " << count << " times." << endl;
}
Everything works fine as far as functionality is concerned; 2+ instances of a word are correctly spotted but they are displayed 2+ times as their own rows, because the instance repeats itself whenever that duplicate element is encountered on the outer loop.
Here's a picture: Basic Result Promblem, Duplicate Output
I thought I'd solve it with the following code:
//Sort vector into alphabetical order
sort(words.begin(), words.end()); //this only sorts them alphabetically, but equal strings are "next" to each other
//Find unique values
for(string::size_type i=0; i != words.size(); i++) {
int count = 0;
for(string::size_type j=0; j != words.size(); j++) {
if(words[i] == words[j]){
count++;
if(i != j){ //replacement: delete duplicate values from the vector (aka if the indexes don't match)
words.erase(words.begin() + j); //delete element at index "j"
}
}
}
cout << words[i] << " appeared: " << count << " times." << endl;
}
A new problem arises with this: the word that appears 2+ times now throws an error. The index itself would work fine, i.e if I were to add cout << words[i] << endl;
right after deleting the element it displays the correct word. However, the word that appears 2+ times does not show up at all, and returns an error.
Here's a picture: Updated problem, now duplicate values throw an error
Anyone would be nice enough to explain why this happens, and how to fix it?