C++ - List Part 2: Adding and Removing Elements
std::list provides efficient methods for inserting and removing elements at any position.
Examples and Explanation
Adding Elements
myList.push_back(10); // Adds 10 to the end
myList.push_front(20); // Adds 20 to the front
Explanation: push_back() and push_front() add elements to the end and the front, respectively.
Removing Elements
myList.pop_back(); // Removes the last element
myList.pop_front(); // Removes the first element
Explanation: Use pop_back() and pop_front() to remove elements from the respective ends of the list.
Inserting at a Specific Position
auto it = myList.begin();
std::advance(it, 1); // Move iterator to the second position
myList.insert(it, 15);
Explanation: The insert() method allows inserting elements at a specific position using iterators.
Removing by Value
myList.remove(10); // Removes all elements with value 10
Explanation: The remove() method eliminates all instances of a specific value from the list.