C++ 中的唯一字数统计帮助?

发布于 2024-10-03 23:55:45 字数 224 浏览 0 评论 0原文

我想做一个可以计算唯一单词的函数。例如:

“我喜欢编写一些有用的东西。而且我喜欢吃东西。现在就吃冰淇淋吧。”

在这种情况下,每个独特的词:

I occurs 2
like occurs 2
...

我稍后会忽略这种情况。请帮助

编辑:

我已经完成了函数的编写。它工作完美。感谢您的所有帮助。非常感谢。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

夏至、离别 2024-10-10 23:55:45

听起来您想使用带有键字符串和数据的 std::map的 int。

如果地图中不存在某个项目,则可以将其添加为 int 值 1。如果该项目已存在于地图中,则只需将 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.

千秋岁 2024-10-10 23:55:45

我会将其视为一个家庭作业问题(希望没有人会如此轻率地提供完整的代码)。

如果您对“单词”的非常宽松的定义感到满意,那么 iostream 输入已经为您将输入拆分为单词。

然后使用例如 std::map 来计算不同的单词。

干杯&呵呵,,

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

悸初 2024-10-10 23:55:45

这是熟悉迭代器和标准算法的绝佳机会。

std::istream_iterator 进行迭代从给定流中提取的单词列表,可以是 std::cin 也可以是文件或字符串。

std::unique 可以帮助您你的目标。

示例程序:

#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));
}

有关标准库的更多参考,请参阅http://www.cplusplus.com

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文