Array Spans and std::span

Creating a Span from a Vector

How can I create a std::span from a std::vector in C++? Can you provide an example?

Abstract art representing computer programming

You can create a std::span from a std::vector by passing the vector to the std::span constructor. Here's an example:

#include <iostream>
#include <span>
#include <vector>

void PrintSpan(std::span<const int> data) {
  for (int i : data) {
    std::cout << i << " ";
  }
  std::cout << "\n";
}

int main() {
  std::vector<int> vec{1, 2, 3, 4, 5};
  std::span<int> span{vec};  

  PrintSpan(span);
}
1 2 3 4 5

In this example, we create a std::vector<int> called vec with some initial values. We then create a std::span<int> called span by passing vec to its constructor.

We can pass span to functions that expect a std::span, like PrintSpan in this example. PrintSpan takes a std::span<const int>, which allows it to read the elements but not modify them.

Note that the std::span does not own the data. If the original std::vector goes out of scope or is modified, the std::span will be affected.

Also, if you have a const std::vector, you should create a std::span<const T> to avoid any accidental modifications:

const std::vector<int> vec{1, 2, 3, 4, 5};
std::span<const int> span{vec};

This way, the constness of the original vector is carried over to the span.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 125 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved