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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 19:00:44  来源:igfitidea点击:

Neatest way to loop over a range of integers

c++

提问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.Rangecontains a few more interesting ranges which you could find pretty useful combined with the new forloop. 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++20we 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 views are lazy. That means even though views::iotarepresents a range from 1to 10exclusive, no more than one intfrom that range exists at one point. The elements are generated on demand.

这种方法view优点在于s 是惰性的。这意味着即使views::iota代表了一个从110独占的int范围,但在一个点上不存在来自该范围的多个。元素是按需生成的

回答by Emilio Garavaglia

Depending on what you have to do with the integer, consider the also the <numeric>header, in particular std::iotain conjunction with std::transformand std::filldepending on the cases.

根据您对整数的处理方式,还可以考虑<numeric>标题,特别 std::iota是结合std::transformstd::fill视情况而定。