Help needed with this C++ code (distinct occurrence related)

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!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace 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;
}
Last edited on
Look at the content of the vector after unique.
¿what's the purpose of the parameter `i' in `count()' ?
Thanks for your reply!

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?

1
2
3
4
while(s[i-1].compare(s[i])==0 && i<limit){
    ++uni_count;
    ++i;
}


And within the for loop below, we add one more line

1
2
3
4
for (auto ite = v.begin(); ite != end; ++ite){
    cout<<(*ite)<<" occurred "<<count(v, i )<<endl;
    ++i;
}
Again, look at your vector after the std::unique()
s[i] == s[i-1] would not hold anymore.

Also, for a counting function I would expect something like
1
2
3
4
5
6
7
count(collection, value){
   cant=0;
   for(K in collection)
      if K==value
         ++cant;
   return cant;
}
Topic archived. No new replies allowed.