How it works...

In this recipe, we will explore what std::span is and why it is needed. In C++ (and even in C), to pass an array to a function, the following is implemented:

void foo(const int *array, size_t size){    for (auto i = 0; i < size; i++) {        std::cout << array[i] << ' ';    }    std::cout << '\n';}

As shown in the preceding example, we have created a function called foo() that takes a pointer to an array as well as the size of the array. We then use this information to output the contents of the array to stdout.

We can execute this function as follows:

int main(void){    int array[] = {4, 8, 15, 16, 23, 42};    foo(array, sizeof(array)/sizeof(array[0]));}

This results in the following output:

The problem with the preceding code is that it is ...

Get Advanced C++ Programming Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.