How to use std::span from C++20 -- Bartlomiej Filipek

How_to_use_std_span_from_C++20.pngIn this article, we’ll look at std::span which is more generic than string_view and can help work with arbitrary contiguous collections.

How to use std::span from C++20

by Bartlomiej Filipek

From the article:

Here’s an example that illustrates the primary use case for std::span:

In traditional C (or low-level C++), you’d pass an array to a function using a pointer and a size like this:

void process_array(int* arr, std::size_t size) {
  for(std::size_t i = 0; i < size; ++i) {
    // do something with arr[i]
  }
}

std::span simplifies the above code:

void process_array(std::span<int> arr_span) {
  for(auto& elem : arr_span) {  
    // do something with elem  
  } 
} 

The need to pass a separate size variable is eliminated, making your code less error-prone and more expressive.

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.