boost中的数值范围迭代器?
我知道 boost 中的范围迭代器,至于 此参考,似乎应该有一种简单的方法来做我想做的事,但对我来说并不明显。
假设我想表示一个数字范围,0 到 100(包含或不包含),例如 range(0,100)
。 我想做一些类似的事情:
for_each(range<int>(0,100).begin(), range<int>(0,100).end(), do_something);
其中 do_something
是一个函子。 这个迭代器不应该有底层向量或类似的东西的开销,而只是提供一个整数序列。 这可以通过 boost 中的范围实现实现吗? 使用普通的标准 STL 迭代器是否可行?
I'm aware of the range iterators in boost, and as for this reference, it seems there should be an easy way of doing what I want, but it's not obvious to me.
Say I want to represent a numerical range, 0 to 100 (inclusive or not), say range(0,100)
. I would like to do something like:
for_each(range<int>(0,100).begin(), range<int>(0,100).end(), do_something);
where do_something
is a functor. This iterators shouldn't have the overhead of having an underneath vector or something like this, but to just offer a sequence of integers. Is this possible with the range implementation in boost? Possible at all with normal, standard STL iterators?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
boost::counting_iterator
boost::counting_iterator
如果您从 C++11 的角度来看,只是为了添加其他答案 - 如果您更愿意使用现代的 for-each 循环,您可以使用 增强计数范围:
输出:
Just to add to the other answers if you're coming from a C++11 perspective - if you'd rather use modern for-each loops, you can do this even more cleanly with boost counting_range:
Outputs:
对的,这是可能的。 看起来 boost::range 不支持开箱即用,但您可以
boost::counting_iterator
,它正是您想要operator*()
将返回一个数字,并将其用作range
的迭代器Yes, it is possible. It just seems boost::range doesn't have support for it out of the box, but you can
boost::counting_iterator
, which does just what you wantoperator*()
would return a number, and use that as an iterator forrange