Is there a range class in C++11 for use with range based for loops?(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).
这篇关于C++11 中是否有一个范围类可用于基于范围的 for 循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++11 中是否有一个范围类可用于基于范围的 for 循环?
基础教程推荐
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- CString 到 char* 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
