Neatest way to loop over a range of integers

后端 未结 4 1298
感情败类
感情败类 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 
    #include 
    
    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.

提交回复
热议问题