Question

I would like to do a function which can count the unique words. For example:

"I like to program something useful. And I like to eat. Eat ice-cream now."

In this case, each unique words:

I occurs 2
like occurs 2
...

I will ignore the case later on. Please help

EDIT:

I have finished write the functions. It works perfectly. Thanks for all the help. Very much appreciated.

Was it helpful?

Solution

Sounds like you want to use an std::map with a key string and data of int.

If an item doesn't exist in the map already you add it with an int value of 1. If the item does exist in the map already you simply add 1 to its associated value.

OTHER TIPS

I'll treat this as a homework question (hopefully no-one will be so thoughtless as to present complete code).

If you're content with a very loose definition of "word", then iostream input already splits the input into words for you.

Then use e.g. std::map to count distinct words.

Cheers & hth.,

It is an excellent opportunity to get acquainted with iterators and standard algorithms.

There is std::istream_iterator which iterates on the list of words drawn from a given stream, either std::cin or a file or a string.

There is std::unique which can help you in your goal.

Example program:

#include <algorithm>
#include <iostream>
#include <vector>

using namespace std;


int main()
{
    istream_iterator<string> begin(cin), end;
    vector<string> tmp;

    copy(begin, end, back_inserter(tmp));
    sort(tmp.begin(), tmp.end());
    vector<string>::iterator it = unique(tmp.begin(), tmp.end());

    cout << "Words:\n";
    copy(tmp.begin(), it, ostream_iterator<string>(cout));
}

Please refer to http://www.cplusplus.com for further reference on the standard library.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top