String Views

string_view vs span

What is the difference between std::string_view and std::span?

Abstract art representing computer programming

std::string_view and std::span are both lightweight, non-owning views over a sequence of elements, but they serve different purposes and have different use cases.

std::string_view

  • Specifically designed for strings.
  • Provides read-only access to a string or a substring.
  • Works with std::string, C-style strings, and string literals.
  • Does not allow modification of the underlying string.

Example:

#include <iostream>
#include <string_view>

int main() {
  std::string_view view{"Hello, world"};
  std::cout << view;
}
Hello, world

std::span

  • General-purpose view for any contiguous sequence of elements, such as arrays, vectors, or C-style arrays.
  • Provides both read-only and mutable access (if not const).
  • Can represent a subrange of the elements.

Example:

#include <iostream>
#include <span>

void printSpan(std::span<int> s) {
  for (int i : s) {
    std::cout << i << ' ';
  }
}

int main() {
  int arr[] = {1, 2, 3, 4, 5};
  std::span<int> sp{arr};
  printSpan(sp);
}
1 2 3 4 5

Key Differences

  • Specialization vs. Generalization: std::string_view is specialized for strings, while std::span is generalized for any type of sequence.
  • Mutability: std::string_view is read-only, whereas std::span can be mutable or immutable depending on its type.
  • Functionality: std::span provides more general functionality like iterating over elements of any type, while std::string_view includes string-specific methods like substr().

Use Cases

  • Use std::string_view when working specifically with strings and need a read-only view.
  • Use std::span when you need a view over any contiguous sequence of elements and might need to modify the elements.

Both types improve performance by avoiding unnecessary copies and providing safe access to sequences, but they cater to different needs.

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:

  • 124 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