C++ 中的唯一字数统计帮助?
我想做一个可以计算唯一单词的函数。例如:
“我喜欢编写一些有用的东西。而且我喜欢吃东西。现在就吃冰淇淋吧。”
在这种情况下,每个独特的词:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
听起来您想使用带有键字符串和数据的 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.
我会将其视为一个家庭作业问题(希望没有人会如此轻率地提供完整的代码)。
如果您对“单词”的非常宽松的定义感到满意,那么 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.,
这是熟悉迭代器和标准算法的绝佳机会。
有
std::istream_iterator
进行迭代从给定流中提取的单词列表,可以是std::cin
也可以是文件或字符串。有
std::unique
可以帮助您你的目标。示例程序:
有关标准库的更多参考,请参阅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, eitherstd::cin
or a file or a string.There is
std::unique
which can help you in your goal.Example program:
Please refer to http://www.cplusplus.com for further reference on the standard library.