C ++ 11中是否存在用于基于范围的for循环的范围类? [英] Is there a range class in C++11 for use with range based for loops?

查看:73
本文介绍了C ++ 11中是否存在用于基于范围的for循环的范围类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚发现自己写了这篇文章:

I found myself writing this just a bit ago:

template <long int T_begin, long int T_end>
class range_class {
 public:
   class iterator {
      friend class range_class;
    public:
      long int operator *() const { return i_; }
      const iterator &operator ++() { ++i_; return *this; }
      iterator operator ++(int) { iterator copy(*this); ++i_; return copy; }

      bool operator ==(const iterator &other) const { return i_ == other.i_; }
      bool operator !=(const iterator &other) const { return i_ != other.i_; }

    protected:
      iterator(long int start) : i_ (start) { }

    private:
      unsigned long i_;
   };

   iterator begin() const { return iterator(T_begin); }
   iterator end() const { return iterator(T_end); }
};

template <long int T_begin, long int T_end>
const range_class<T_begin, T_end>
range()
{
   return range_class<T_begin, T_end>();
}

这允许我写这样的东西:

And this allows me to write things like this:

for (auto i: range<0, 10>()) {
    // stuff with i
}

现在,我知道我写的也许不是最好的代码。也许有一种方法可以使它更加灵活和有用。但是在我看来,这样的事情应该已经成为标准的一部分。

Now, I know what I wrote is maybe not the best code. And maybe there's a way to make it more flexible and useful. But it seems to me like something like this should've been made part of the standard.

是吗?是为整数范围内的迭代器添加了某种新库,还是为计算标量值的一般范围添加了新库?

So is it? Was some sort of new library added for iterators over a range of integers, or maybe a generic range of computed scalar values?

推荐答案

C ++标准库没有一个,但是 Boost.Range具有boost :: counting_range ,当然可以。您还可以使用 boost :: irange ,它的作用域更加集中。

The C++ standard library does not have one, but Boost.Range has boost::counting_range, which certainly qualifies. You could also use boost::irange, which is a bit more focused in scope.

C ++ 20的范围库将允许您通过 view :: iota(开始,结束)

C++20's range library will allow you to do this via view::iota(start, end).

这篇关于C ++ 11中是否存在用于基于范围的for循环的范围类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆