Is there a way to iterate over at most N elements using range-based for loop?

As I personally would use either this or this answer (+1 for both), just for increasing your knowledge – there are boost adapters you can use. For your case – the sliced seems the most appropriate:

#include <boost/range/adaptor/sliced.hpp>
#include <vector>
#include <iostream>

int main(int argc, const char* argv[])
    std::vector<int> input={1,2,3,4,5,6,7,8,9};
    const int N = 4;
    using boost::adaptors::sliced;
    for (auto&& e: input | sliced(0, N))
        std::cout << e << std::endl;

One important note: N is required by sliced to be not greater than distance(range) – so safer(and slower) version is as follows:

    for (auto&& e: input | sliced(0, std::min(N, input.size())))

So – once again – I would use simpler, old C/C++ approach (this you wanted to avoid in your question 😉

Leave a Comment