Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C++ erase function

C++ erase function

C++ Container Class The C++ container class


erase is used in list toremoves the element at a specified position.

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

In list,erase has a time complexity of O(1), because only pointers need to be adjusted.

Word meaning: erase means "erase," i.e., to remove the element at the specified position.


Basic syntax and parameters

erase is a member function of the container class.

Syntax format



iterator erase(iterator pos);

iterator erase(iterator first, iterator last);

Parameter Description

Function description


Example

Example 1: Delete a single element

Example

#include

#include

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

;

   

// Delete 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 output:

原始: 1 2 3 4 5

删除后: 1 3 4 5

Example 2: Delete multiple elements

Example

#include

#include

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

;

   

// Delete the 2nd through 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 output:

原始: 1 2 3 4 5 6 7

删除后: 1 5 6 7


C++ Container Class The C++ container class