C++ <list> erase Function

C++ container class <list>


eraseis used in list fordeleting elements at specified positionsof the function.

eraseIt is a member function of the container class, used to delete one or more elements at a specified position in the linked list.

In the list,eraseIts time complexity is O(1), because it only requires adjusting pointers.

Word Definitions: eraseIt means "erase," i.e., deleting the element at the specified position.


Basic Syntax and Parameters

eraseis a member function of the container class.

Syntax format

iterator erase(iterator pos);
iterator erase(iterator first, iterator last);

Parameter description

  • Parameter: pos- position of the element to be deleted
  • Parameter: first, last- range of the elements to be deleted

Function description

  • Return Value: Returns an iterator pointing to the next element.
  • Effect: deletes the element at the specified position.

Example

Example 1: Deleting a single element

Example

#include <iostream>
#include <list>

int main() {
    std::list<int> numbers = {1, 2, 3, 4, 5};

    std::cout << "Original: ";
    for(int n : numbers) std::cout << n << " ";
    std::cout << std::endl;

    // Remove the second element
    auto it = std::next(numbers.begin(), 1);
    numbers.erase(it);

    std::cout << "After deletion: ";
    for(int n : numbers) std::cout << n << " ";
    std::cout << std::endl;

    return 0;
}

Expected Running Result:

原始: 1 2 3 4 5
After deletion: 1 3 4 5

Example 2: Deleting multiple elements

Example

#include <iostream>
#include <list>

int main() {
    std::list<int> numbers = {1, 2, 3, 4, 5, 6, 7};

    std::cout << "Original: ";
    for(int n : numbers) std::cout << n << " ";
    std::cout << std::endl;

    // Erase the 2nd to 4th elements
    auto first = std::next(numbers.begin(), 1);
    auto last = std::next(numbers.begin(), 4);
    numbers.erase(first, last);

    std::cout << "After deletion: ";
    for(int n : numbers) std::cout << n << " ";
    std::cout << std::endl;

    return 0;
}

Expected Running Result:

原始: 1 2 3 4 5 6 7
After deletion: 1 5 6 7

C++ container class <list>

other extensions