Is it possible to loop over a vector based on a predefined range?
I need something like this:
for(auto& it : myvector[0, 30])
Or:
for(auto& it : myvector[0-30])
Is this posible anyway? I've tried both ways but it don't works.
the shortest code to do that is using an std::span as follow.
#include <iostream>
#include <vector>
#include <span>
int main()
{
    std::vector<int> vec{1,2,3,4};
    // starting at 1, take 2 elements
    for (auto&& val: std::span(vec).subspan(1,2))
    {
        std::cout << val << '\n';  // print 2 and 3
    }
}
you can simplify the code with a helper as follows;
#include <iostream>
#include <vector>
#include <span>
#include <cstdint>
// end exclusive
auto slice(auto& vec, size_t start, size_t end)
{
    return std::span(vec).subspan(start,end-start);
}
int main()
{
    std::vector<int> vec{1,2,3,4};
    for (auto&& val: slice(vec,1,3))
    {
        std::cout << val << '\n';
    }
}
this helper also works with C arrays. ex: int vec[] = {1,2,3,4}; and std::array, std::array<int, 4> vec = {1,2,3,4};.
Edit: after writing this i realized this is the easiest way to segfault your application, so you should assert on the bounds when creating the span or clip to the bounds to protect the user passing an invalid range.
constexpr auto slice(auto& vec, size_t start, size_t end)
{
    assert(end <= std::size(vec));
    return std::span(vec).subspan(start,end-start);
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With