On this page
std::span
Prev: std::array | Up: containers | Next: std::map
Rel: std::vector, std::array, std::string_view, Ranges & Span Pipeline Tutorial
Ref: cppreference — std::span
Tags: #public #prog #cpp #stdlib #containers #tier/standard
Overview
std::span<T> (<span>, C++20) is a non-owning (T* data, std::size_t size) view over any contiguous sequence (std::vector, std::array, or C array). It replaces error-prone (const T* ptr, size_t len) parameter pairs.
Notes & Pitfalls
- C++20 non-owning contiguous view (
T*+size_t): Passstd::span<const T>by value instead of(const T* ptr, size_t len)orconst std::vector<T>&. - Never outlive the underlying container:
spandoes not own memory.
Example
#include <array>
#include <cassert>
#include <span>
#include <vector>
int sum(std::span<const int> xs) {
int total = 0;
for (int v : xs) total += v;
return total;
}
int main() {
std::vector<int> v{1, 2, 3};
std::array<int, 2> a{4, 5};
assert(sum(v) == 6 && sum(a) == 9);
}
Linked from
- tuts/cpp/language_and_raii/raii_smart_pointers_and_lifetime
- tuts/cpp/stdlib/algorithm_and_ranges/ranges_views
- tuts/cpp/stdlib/containers
- tuts/cpp/stdlib/containers/array
- tuts/cpp/stdlib/containers/map
- tuts/cpp/stdlib/containers/string_view
- tuts/cpp/stdlib/containers/vector
- tuts/cpp/tutorials/ranges_and_span_data_pipeline
Related notes
- tuts/cpp/stdlib/containers/array Linked here; links to this page; shared tags: #containers, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/containers/map Linked here; links to this page; shared tags: #containers, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/containers/string_view Linked here; links to this page; shared tags: #containers, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/containers/vector Linked here; links to this page; shared tags: #containers, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/containers Linked here; links to this page; shared tags: #containers, #cpp, #prog, #stdlib
- tuts/cpp/tutorials/ranges_and_span_data_pipeline Linked here; links to this page; shared tags: #cpp, #prog, #tier
- tuts/cpp/stdlib/algorithm_and_ranges/ranges_views links to this page; shared tags: #cpp, #prog, #stdlib, #tier
- tuts/cpp/language_and_raii/raii_smart_pointers_and_lifetime links to this page; shared tags: #cpp, #prog, #tier
- tuts/cpp/stdlib/containers/expected shared tags: #containers, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/containers/optional shared tags: #containers, #cpp, #prog, #stdlib, #tier