In modern C++, std::span
is an excellent way to bridge the gap between legacy arrays and pointers, providing a safer and more convenient way to work with contiguous sequences of elements. This flexibility allows developers to interact with legacy C-style arrays while maintaining the benefits of modern C++ constructs.
std::span
is a lightweight, non-owning view into a sequence of elements, which can be especially useful when dealing with legacy code. Below is an example demonstrating how to create a std::span
from a legacy C-style array, as well as from a pointer and size.
#include
#include
void processSpan(std::span s) {
for (int num : s) {
std::cout << num << " ";
}
std::cout << std::endl;
}
int main() {
int legacyArray[] = {1, 2, 3, 4, 5};
std::span spanFromArray(legacyArray); // Create a span from a C-style array
processSpan(spanFromArray);
int* legacyPointer = new int[5]{6, 7, 8, 9, 10};
std::span spanFromPointer(legacyPointer, 5); // Create a span from a pointer and size
processSpan(spanFromPointer);
delete[] legacyPointer; // Don't forget to clean up
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?