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 循环?


基础教程推荐
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 这个宏可以转换成函数吗? 2022-01-01