Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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++

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
182 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...