12

How do I create a ranges-v3-compatible range, given a traditional pair of "begin" and "end" iterators?

Let's say that I am writing a generic function that accepts two iterators, for compatibility with legacy code.

struct result;  

bool keep_line(const std::string&);
result parse_line(const std::string&);

template <typename InputIt>
std::vector<result> parse_lines(InputIt begin, InputIt end)
{
    // This is what I want to do...
    auto lines = ranges::make_range_out_of_legacy_iterators(begin, end);

    return lines 
        | ranges::view::filter(keep_line) 
        | ranges::view::transform(parse_line) 
        | ranges::to<std::vector<result>>();
}
NicholasM
  • 4,557
  • 1
  • 20
  • 47

1 Answers1

14

To create a range from a pair of iterators in ranges-v3, use the subrange view:

#include <range/view/subrange.hpp>

auto lines = ranges::subrange(begin, end);       // Requires C++17-style deduction

auto lines = ranges::make_subrange(begin, end);  // If template deduction not available

In old versions of the library, the iterator_range class in range/v3/iterator_range.hpp was apparently used, but that header is marked deprecated in the current ranges-v3 release (0.9.1).

NicholasM
  • 4,557
  • 1
  • 20
  • 47
  • Is it the same for C++20 ranges. – L. F. Oct 10 '19 at 12:28
  • @L.F.: yes, it should be the same under C++20, based on the [cppreference page](https://en.cppreference.com/w/cpp/ranges). The page for the `subrange` view specifically does not exist on cppreference at this time. – NicholasM Oct 10 '19 at 18:11
  • 1
    As a follow-up question, how did you find this out? The reference API you linked seems to contain no reference information beyond the name of the types and methods. Is there some source with actual reference material? I'm exploring the library and I can't seem to find anything that describes the parts of it. – Ayjay Nov 21 '20 at 17:42
  • @Ayjay My recollection is that I searched through [some documentation](https://ericniebler.github.io/range-v3/dir_b00b1d9d00cc44a1bf5374fbcb141bf4.html), and focused on finding a range that had a constructor with the right type signature (accepting an iterator and a sentinel), and was effectively a no-op (as `subrange` is). – NicholasM Nov 21 '20 at 20:13