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>();
}
这让我可以这样写:
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(start, end)
.
C++20's range library will allow you to do this via view::iota(start, end)
.
相关文章