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

C++ offers a powerful standard library that includes various container types, one of which is the `std::list`. The `std::list` is a doubly linked list that allows for efficient insertion and deletion of elements at any position, making it an ideal choice for scenarios where these operations need to be performed frequently.

Efficient Insertion and Erasure with std::list

Inserting and erasing elements in a `std::list` is efficient because the operations do not require shifting elements, as is the case with vector or array types. Here’s an example showcasing how to perform these operations:

#include <iostream> #include <list> int main() { std::list<int> myList; // Inserting elements myList.push_back(10); // Insert 10 at the end myList.push_front(20); // Insert 20 at the beginning auto it = myList.begin(); std::advance(it, 1); // Move iterator to the second position myList.insert(it, 30); // Insert 30 at the second position std::cout << "List after insertion: "; for (const auto& elem : myList) { std::cout << elem << " "; } std::cout << std::endl; // Erasing elements myList.erase(it); // Erase the element at the second position std::cout << "List after erasure: "; for (const auto& elem : myList) { std::cout << elem << " "; } std::cout << std::endl; return 0; }

C++ std::list insertion erasure efficient data structures C++ standard library