In C++, std::span
is a lightweight proxy object that provides a view over a contiguous sequence of elements, available in C++20. It allows you to operate on arrays and other sequences without having to pass pointers and sizes separately. This can improve code readability and safety.
Here’s how to construct and use std::span
in your C++ code:
#include
#include
#include
void printSpan(std::span s) {
for (int i : s) {
std::cout << i << " ";
}
std::cout << std::endl;
}
int main() {
// Using std::array
std::array arr = {1, 2, 3, 4, 5};
std::span span1 = arr; // Span over std::array
printSpan(span1);
// Using std::vector
std::vector vec = {6, 7, 8, 9, 10};
std::span span2 = vec; // Span over std::vector
printSpan(span2);
// Using raw arrays
int rawArray[] = {11, 12, 13, 14, 15};
std::span span3(rawArray, 5); // Span over raw array
printSpan(span3);
return 0;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?