Generating a ranges::view from a raw pointer (decayed C style array) and a size

Viewed 757

Using a function from a C library providing a pointer and a size, is there (or will there be) a way to generate a ranges::view directly from it ? As I understood, views need a begin iterator and a sentinel, so will I have to copy the content of the decayed C array into a vector to be able to use views in that case ?

2 Answers

You wont need to make any sort of copy. Along with ranges, C++20 will also have std::span which takes a pointer and a size and treats it as a container. You can then pass that to all of the ranges functions. That would look like

std::size_t size;
auto ptr = c_function_call(&size); // or however you get the pointer and size from the c function
std::span container{ptr, size};
// use container with any view you want here

If std::span is not available, you can take advantage of the fact that a pointer is a C++ iterator.

Given a pointer p and a size n, you can use the pair of iterators [p, p + n) to construct a range using ranges::subrange:

void print(int i) { std::cout << i << " "; }

int values[6] = {0, 1, 2, 3, 4, 5};

// Example of a pointer and a size.
const int* ptr = values;
const std::size_t n = 3;

auto r = ranges::subrange(ptr, ptr + n);
ranges::for_each(r, print);  // Prints:  0, 1, 2

Working example: https://wandbox.org/permlink/eeIa96ieCb8GIQcM

Related