Unique word count in C++ help?

风流意气都作罢 提交于 2019-12-08 03:57:45

问题


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.


回答1:


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.




回答2:


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.,




回答3:


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.



来源:https://stackoverflow.com/questions/4238395/unique-word-count-in-c-help

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!