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

C++ remove function

C++ remove function

C++ Container Class The C++ container class


remove is used in list toremoves all elements equal to a specified valuefunction; it is a list-specific efficient operation.

remove is a member function of the container class, used to remove all elements in the linked list that are equal to a specified value.

In list,remove has a time complexity of O(n).

Word meaning: remove means "remove," i.e., to remove all elements equal to the specified value.


Basic syntax and parameters

Syntax format



void remove(const T& value);

Parameter Description

Function description


Example

Example 1: Remove all elements equal to a specified value

Example

#include

#include

int

main

(

)

{

    std

::

list

<

int

numbers

=

{

1

,

2

,

3

,

2

,

4

,

2

,

5

}

;

    std

::

cout

<<

"Original: "

;

   

for

(

int

n

:

numbers

)

std

::

cout

<<

n

<<

" "

;

    std

::

cout

<<

std

::

endl

;

   

// Remove all elements equal to 2

    numbers.

remove

(

2

)

;

    std

::

cout

<<

"After remove(2): "

;

   

for

(

int

n

:

numbers

)

std

::

cout

<<

n

<<

" "

;

    std

::

cout

<<

std

::

endl

;

   

return

0

;

}

Expected output:

原始: 1 2 3 2 4 2 5

remove(2) 后: 1 3 4 5

Example 2: Remove a string

Example

#include

#include

#include

int

main

(

)

{

    std

::

list

<

std

::

string

words

=

{

"apple"

,

"banana"

,

"apple"

,

"cherry"

,

"apple"

}

;

    std

::

cout

<<

"Original: "

;

   

for

(

const

auto

&

w

:

words

)

std

::

cout

<<

w

<<

" "

;

    std

::

cout

<<

std

::

endl

;

    words.

remove

(

"apple"

)

;

    std

::

cout

<<

"After remove("apple"): "

;

   

for

(

const

auto

&

w

:

words

)

std

::

cout

<<

w

<<

" "

;

    std

::

cout

<<

std

::

endl

;

   

return

0

;

}

Expected output:

原始: apple banana apple cherry apple

remove("apple") 后: banana cherry


C++ Container Class The C++ container class