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, worldstd::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 5Key Differences
- Specialization vs. Generalization:
std::string_viewis specialized for strings, whilestd::spanis generalized for any type of sequence. - Mutability:
std::string_viewis read-only, whereasstd::spancan be mutable or immutable depending on its type. - Functionality:
std::spanprovides more general functionality like iterating over elements of any type, whilestd::string_viewincludes string-specific methods likesubstr().
Use Cases
- Use
std::string_viewwhen working specifically with strings and need a read-only view. - Use
std::spanwhen 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