遍历整数范围的最巧妙方法 [英] Neatest way to loop over a range of integers

查看:76
本文介绍了遍历整数范围的最巧妙方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

自C ++ 11引入基于范围的for循环(在c中基于范围的for ++ 11 ),最简单的表达整数范围循环的方法是什么?

Since C++11 introduced the range-based for loop (range-based for in c++11), what is the neatest way to express looping over a range of integers?

而不是

for (int i=0; i<n; ++i)

我想写类似

for (int i : range(0,n))

新标准是否支持这种类型的东西?

Does the new standard support anything of that kind?

更新:本文介绍了如何在C ++ 11中实现范围生成器: C ++中的生成器

Update: this article describes how to implement a range generator in C++11: Generator in C++

推荐答案

尽管C ++不提供11,您可以编写自己的视图或使用boost中的视图:

While its not provided by C++11, you can write your own view or use the one from boost:

#include <boost/range/irange.hpp>
#include <iostream>

int main(int argc, char **argv)
{
    for (auto i : boost::irange(1, 10))
        std::cout << i << "\n";
}

此外, Boost.Range 包含更多内容有趣的范围,结合新的 for 循环,您会发现它非常有用。例如,您可以获取反转视图

Moreover, Boost.Range contains a few more interesting ranges which you could find pretty useful combined with the new for loop. For example, you can get a reversed view.

这篇关于遍历整数范围的最巧妙方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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