Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create ranges from two iterators

Tags:

c++

c++20

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.

like image 575
steviekm3 Avatar asked Feb 27 '26 00:02

steviekm3


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;
}
like image 65
metalfox Avatar answered Feb 28 '26 13:02

metalfox