C++ 循环整数范围的最简洁方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15088900/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Neatest way to loop over a range of integers
提问by user1101674
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?
由于 C++11 引入了基于范围的 for 循环(c++11 中的基于范围的 for),那么在整数范围内表达循环的最简洁方法是什么?
Instead of
代替
for (int i=0; i<n; ++i)
I'd like to write something like
我想写一些类似的东西
for (int i : range(0,n))
Does the new standard support anything of that kind?
新标准是否支持此类内容?
Update: this article describes how to implement a range generator in C++11: Generator in C++
更新:本文介绍了如何在 C++11 中实现范围生成器:C++ 中的生成器
采纳答案by ixSci
While its not provided by C++11, you can write your own view or use the one from boost:
虽然 C++11 没有提供它,但您可以编写自己的视图或使用 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";
}
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.
此外,Boost.Range
包含一些更有趣的范围,您会发现这些范围与新for
循环结合使用时非常有用。例如,您可以获得反向视图。
回答by B?ови?
The neatest way is still this:
最简洁的方法仍然是这样:
for (int i=0; i<n; ++i)
I guess you can do this, but I wouldn't call it so neat:
我想你可以做到这一点,但我不会称之为如此整洁:
#include <iostream>
int main()
{
for ( auto i : { 1,2,3,4,5 } )
{
std::cout<<i<<std::endl;
}
}
回答by Fureeish
With C++20
we will have ranges. You can try them by downloading the lastest stable release from it's author, Eric Niebler, from his github, or go to Wandbox. What you are interested in is ranges::views::iota
, which makes this code legal:
随着C++20
我们将有范围。您可以通过从作者 Eric Niebler的 github或转到Wandbox下载最新的稳定版本来试用它们。您感兴趣的是ranges::views::iota
,这使此代码合法:
#include <range/v3/all.hpp>
#include <iostream>
int main() {
using namespace ranges;
for (int i : views::iota(1, 10)) {
std::cout << i << ' ';
}
}
What's great about this approach is that view
s are lazy. That means even though views::iota
represents a range from 1
to 10
exclusive, no more than one int
from that range exists at one point. The elements are generated on demand.
这种方法view
的优点在于s 是惰性的。这意味着即使views::iota
代表了一个从1
到10
独占的int
范围,但在一个点上不存在来自该范围的多个。元素是按需生成的。