Search code examples
c++c++11stlc++14

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


Is there a nice way to iterate over at most N elements in a container using a range-based for loop and/or algorithms from the standard library (that's the whole point, I know I can just use the "old" for loop with a condition).

Basically, I'm looking for something that corresponds to this Python code:

for i in arr[:N]:
    print(i)

Solution

  • Since C++20 you can add the range adaptor std::views::take from the Ranges library to your range-based for loop. This way you can implement a similar solution to the one in PiotrNycz's answer, but without using Boost:

    int main() {
        std::vector<int> v {1, 2, 3, 4, 5, 6, 7, 8, 9};
        const int N = 4;
    
        for (int i : v | std::views::take(N))
            std::cout << i << std::endl;
            
        return 0;
    }
    

    The nice thing about this solution is that N may be larger than the size of the vector. This means, for the example above, it is safe to use N = 13; the complete vector will then be printed.

    Code on Wandbox