fenbf / cppstories-discussions

4 stars 1 forks source link

2023/span-cpp20/ #134

Open utterances-bot opened 11 months ago

utterances-bot commented 11 months ago

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

In this article, we’ll look at std::span which is more generic than string_view and can help work with arbitrary contiguous collections. A Motivating Example   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:

https://www.cppstories.com/2023/span-cpp20/

ormandi commented 11 months ago

Thank you for the great summary! I assume in the examples of the section “ From Iterators and Size” the value of count could be 3 as well and by using the value 2 only the first two elements captured.

fenbf commented 11 months ago

Thanks for the comment @ormandi . Yes, you can specify the count starting from the first element. I updated the text to make it more clear and also with a better example, https://godbolt.org/z/xbvMxM915

bekard commented 11 months ago

Thanks!

VictorEijkhout commented 11 months ago

Yes yes yes, it's a lightweight thingummy and it's better than c-pointers or [] arrays. Sure. But why does this article, and with it just about any video that I've seen, not show the major use case? A span is non-owning, so passing it to a function it can work on a subset of data owned by someone else! You can have a vector of data, and let two threads process two halves of it! Brilliant! And no one explains this. Why?

fenbf commented 10 months ago

Thanks for the inspiration @VictorEijkhout - see my new article: C++20, Spans, Threads and Fun - C++ Stories. Does it look fine to you? :)

VictorEijkhout commented 10 months ago

I’m flattered. That’s a great article, illustrating several advanced or at least recent techniques. Thanks for mentioning me.

Victor.

olesenm commented 10 months ago

The concept of std::span is so handy that we quickly knocked together our own version to start using it without needing to wait for C++20.

If anyone wants it (GPL-3.0-or-later) it is within the OpenFOAM stdFoam.H - not 100% complete according to the standards, but has most of the really useful bits.

VictorEijkhout commented 10 months ago

And of course in applications like scientific computing what you actually want is mdspan....

olesenm commented 10 months ago

And of course in applications like scientific computing what you actually want is mdspan....

Unfortunately mdspan would only be useful for dense (or mostly dense) matrices. Probably have to wait for C++26 BLAS support to come or use Eigen3, Petsc etc.

VictorEijkhout commented 10 months ago

Unfortunately mdspan would only be useful for dense (or mostly dense) matrices.

No actually. In physical applications the domain of definition is often a 2D or 3D brick. So even if your operator is a sparse matrix, your "vector" is still a Cartesian brick.