Hey there, I am supposed to write a code that counts "how many times each distinct word appears within a string input". The code I come up with was shown below, which would output the distinct words with no problem but cannot count the right occurrence for each word. I figured it was some kinda logic error but just couldn't crack it. Any help would be appreciated!
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
usingnamespace std;
//Read words in a string into vector
vector<string> read(istream& in, string input){
vector<string> words;
while (in >> input)
words.push_back(input);
return words;
}
//Count the distinct occurrence, which I suppose is the question mark
int count(vector<string> const&s, int i){
auto limit = s.size();
int uni_count = 1;
while(i<limit){
if (s[i-1].compare(s[i])==0)
uni_count++;
++i;
}
return uni_count;
}
int main(){
string in;
vector<string> v;
cout << "This program shall count how many time each words occured in the input" << endl;
v = read(cin, in); //store the vector
sort(v.begin(), v.end()); //sorting
if (v.size() != 0){
int i = 1;
auto end = unique(v.begin(), v.end()); //returns the end pointer of the unique elements.
for (auto ite = v.begin(); ite != end; ++ite){
cout << (*ite) << " occurred " << count(v, i) << endl;
}
}
return 0;
}
What I wanted to achieve is to make index variable ' i ' increase if a repeat of words was found, and store the ' i ' value for use in the next while loop. Maybe this code will do the work?