Unique word count in C++ help?

巧了我就是萌 提交于 2019-12-06 07:44:55

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.

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.

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