How to create ranges from two iterators

Viewed 651

Am new to using c++20 ranges. One question I have is if you have two iterators into a vector how do you create a ranges view from them ? Range would start at first iterator and end 1 before the second iterator.

1 Answers

std::ranges::subrange allows combining together an iterator and a sentinel into a single view.

For example:

#include <iostream>
#include <vector>
#include <ranges>

int main()
{
    std::vector v = {1, 2, 3, 4, 5};

    std::ranges::subrange w(v.begin(), v.begin() + 2);
    
    for (auto i : w)
      std::cout << i << std::endl;
}
Related