How do I insert and erase elements efficiently with std::span?

C++, std::span, insert elements, erase elements, efficient insertion, efficient erase
Learn how to efficiently insert and erase elements in C++ using std::span. This guide provides examples and best practices.

#include <span>
#include <iostream>
#include <vector>

template<typename T>
void insert(std::span<T> span, size_t index, const T& value) {
    // Create a new vector to hold the elements
    std::vector<T> vec(span.begin(), span.end());
    
    // Insert the value at the specified index
    vec.insert(vec.begin() + index, value);
    
    // Create a new span from the modified vector
    std::span<T> newSpan(vec.data(), vec.size());
    
    // Output the new span elements
    for (const auto& e : newSpan) {
        std::cout << e << ' ';
    }
    std::cout << std::endl;
}

template<typename T>
void erase(std::span<T> span, size_t index) {
    // Create a new vector to hold the elements
    std::vector<T> vec(span.begin(), span.end());
    
    // Erase the element at the specified index
    vec.erase(vec.begin() + index);
    
    // Create a new span from the modified vector
    std::span<T> newSpan(vec.data(), vec.size());
    
    // Output the new span elements
    for (const auto& e : newSpan) {
        std::cout << e << ' ';
    }
    std::cout << std::endl;
}

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    std::span<int> mySpan(arr);

    std::cout << "Insert 10 at index 2: ";
    insert(mySpan, 2, 10);

    std::cout << "Erase element at index 1: ";
    erase(mySpan, 1);

    return 0;
}
    

C++ std::span insert elements erase elements efficient insertion efficient erase