boost中的数值范围迭代器?

发布于 2024-07-14 02:34:00 字数 489 浏览 3 评论 0原文

我知道 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 技术交流群。

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

发布评论

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

评论(3

我家小可爱 2024-07-21 02:34:00

boost::counting_iterator

#include <boost/iterator/counting_iterator.hpp>

std::for_each( boost::counting_iterator<int>(0),
               boost::counting_iterator<int>(100),
               do_something );

boost::counting_iterator

#include <boost/iterator/counting_iterator.hpp>

std::for_each( boost::counting_iterator<int>(0),
               boost::counting_iterator<int>(100),
               do_something );
好听的两个字的网名 2024-07-21 02:34:00

如果您从 C++11 的角度来看,只是为了添加其他答案 - 如果您更愿意使用现代的 for-each 循环,您可以使用 增强计数范围

#include <boost/range/counting_range.hpp>

for(auto const &i : boost::counting_range(0, 10)) {
  std::cout << i;
}

输出:

0123456789

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:

#include <boost/range/counting_range.hpp>

for(auto const &i : boost::counting_range(0, 10)) {
  std::cout << i;
}

Outputs:

0123456789

心不设防 2024-07-21 02:34:00

对的,这是可能的。 看起来 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

  • use boost::counting_iterator, which does just what you want
  • implement a number-like object whose operator*() would return a number, and use that as an iterator for range
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文