On this page
  1. std::span
  2. Overview
  3. Notes & Pitfalls
  4. Example

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

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

Related notes