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

Using std::forward_list in C++ allows you to efficiently manage a singly linked list with unique features such as constant-time insertion and deletion at the front of the list. However, keep in mind that inserting or erasing elements from the middle or end of the list requires a traversal, which can be less efficient compared to other container types.

Example of Inserting and Erasing Elements with std::forward_list


#include <forward_list>
#include <iostream>

int main() {
    std::forward_list<int> myList = {1, 2, 3};

    // Inserting elements
    myList.push_front(0); // Inserts '0' at the front
    myList.insert_after(myList.before_begin(), 4); // Inserts '4' before the first element

    // Displaying the list
    std::cout << "List after insertion: ";
    for (const auto& value : myList) {
        std::cout << value << " ";
    }
    std::cout << std::endl;

    // Erasing elements
    myList.remove(2); // Removes '2' from the list

    // Displaying the list after deletion
    std::cout << "List after deletion: ";
    for (const auto& value : myList) {
        std::cout << value << " ";
    }
    std::cout << std::endl;

    return 0;
}
    

C++ std::forward_list insertion deletion linked list