string_view
vs span
What is the difference between std::string_view
and std::span
?
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, whilestd::span
is generalized for any type of sequence. - Mutability:
std::string_view
is read-only, whereasstd::span
can be mutable or immutable depending on its type. - Functionality:
std::span
provides more general functionality like iterating over elements of any type, whilestd::string_view
includes string-specific methods likesubstr()
.
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.
String Views
A practical introduction to string views, and why they should be the main way we pass strings to functions