All Contiguous-Container and View Relationships
All Contiguous-Container and View Relationships
A compact scan page for how vector, array, string, string_view, span, and mdspan relate through contiguous storage and borrowing semantics.
All Contiguous-Container and View Relationships
A compact scan page for how vector, array, string, string_view, span, and mdspan relate through contiguous storage and borrowing semantics.
Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.
std::vectorstd::arraystd::basic_stringstd::spanstd::string_viewstd::mdspanvector, array, or string can expose a contiguous buffer through data()span can borrow contiguous elements from arrays, vectors, and similar storagestring_view borrows character sequences without ownershipmdspan layers multidimensional indexing over existing storage rather than owning it#include <span>
#include <vector>
void scale(std::span<int> values) {
for (int& value : values) {
value *= 2;
}
}
int main() {
std::vector<int> values{1, 2, 3};
scale(values);
return values[2];
}
The important point is that std::span borrows the vector's storage. That makes the API lightweight, but the vector must outlive the span and must not reallocate while borrowed views are still in use.
std::span<T> for borrowed contiguous elementsstd::string_view for borrowed character sequencesstd::mdspan when the data is still borrowed but indexed as a matrix or tensorvector, array, and string as the owning storage types#include <span>
#include <vector>
void normalize(std::span<int> values) {
for (int& value : values) {
value *= 2;
}
}
int main() {
std::vector<int> values{1, 2, 3};
normalize(values);
return values[1];
}