Neatest way to loop over a range of integers

后端 未结 4 1279
感情败类
感情败类 2020-12-17 07:28

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?

Instead of

相关标签:
4条回答
  • 2020-12-17 08:08

    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";
    }
    

    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.

    0 讨论(0)
  • 2020-12-17 08:22

    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;
      }
    }
    
    0 讨论(0)
  • 2020-12-17 08:24

    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:

    #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::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.

    0 讨论(0)
  • 2020-12-17 08:26

    Depending on what you have to do with the integer, consider the also the <numeric> header, in particular std::iota in conjunction with std::transform and std::fill depending on the cases.

    0 讨论(0)
提交回复
热议问题