How do I avoid iterator invalidation with std::span?

When working with C++ Standard Library containers, iterator invalidation can be a significant concern. However, using `std::span` can help you manage a lightweight view over a contiguous sequence without the risk of iterator invalidation that you would face with some collections. This is particularly useful when you need to provide a view over an array or a vector without modifying the underlying storage.

Here's how you can avoid iterator invalidation using `std::span`:

#include #include #include void processSpan(std::span spans) { for (int element : spans) { std::cout << element << " "; } std::cout << std::endl; } int main() { std::vector vec = {1, 2, 3, 4, 5}; std::span spn(vec.data(), vec.size()); // Create a span processSpan(spn); // Pass the span to a function // Even if we modify the original vector later, the span itself remains valid vec.push_back(6); // Note: We'd need to create a new span if we want to include the new element std::span newSpn(vec.data(), vec.size()); processSpan(newSpn); return 0; }

C++ std::span iterator invalidation vector programming C++ alternatives