In one of my programs for school, I use the following function to count the frequency of identifiers in a string, separated by newlines and #:
Input:
dog
cat
mouse
#
rabbit
snake
#
Function:
//assume I have the proper includes, and am using namespace std
vector< pair<string,int> > getFreqcounts(string input) {
vector<string> items = splitString(input,"\n");
map<string,int> counts;
for (int i=0; i<items.size(); i++) {
if (items[i] == "#") continue;
counts[items[i]] = 0;
}
for (int i=0; i<items.size(); i++) {
if (items[i] == "#") continue;
counts[items[i]]++;
}
return vector< pair<string,int> > (counts.begin(),counts.end());
}
I would like to at the very least
- remove the double for loop
- find a better way to get a
vector< pair<string,int> >
Any ideas?
BTW, this is NOT homework. The real homework will use this function, but this is purely out of my own curiosity and desire to have "better" code.