C++ Deque::erase() Function



The C++ std::deque::erase() function is used to remove an element specified by the iterator or a range from the deque. It can delete a single element at a given position or a range of elements defined by two iterators. After erasing, it adjusts the size of the deque accordingly.

This function has 2 polymorphic variants: with position version or range version (you can find the syntaxes of all the variants below).

Syntax

Following is the syntax for std::deque::erase() function.

iterator erase (const_iterator position );
or
iterator erase (const_iterator first, const_iterator last );

Parameters

  • position − It indicates the iterator pointing to a single element to be removed.
  • first, last − It indicates the iterators specifying a range in deque to remove the element.

position − Iterator points to the deque element.

Return value

It returns an iterator pointing to the new location of the element.

Exceptions

It throws an exception (undefined behaviour), if position is invalid.

Time complexity

The time complexity of this function is Linear i.e. O(n)

Example

Let's look at the following example, where we are going to use the position version to erase the element.

#include <iostream>
#include <deque>
int main()
{
    std::deque<char> a = {'A', 'B', 'C', 'D', 'E'};
    auto x = a.begin() + 2;
    a.erase(x);
    for (char num : a) {
        std::cout << num << " ";
    }
    std::cout << std::endl;
    return 0;
}

Output

Output of the above code is as follows −

A B D E 

Example

Consider the another scenario, where we are going to erase the elements using range version.

#include <iostream>
#include <deque>
int main()
{
    std::deque<int> a = {1, 22,321,4321,12345};
    auto x = a.begin() + 1;
    auto y = a.begin() + 4;
    a.erase(x, y);
    for (auto num : a) {
        std::cout << num << " ";
    }
    std::cout << "\n";
    return 0;
}

Output

Following is the output of the above code −

1 12345
deque.htm
Advertisements