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

C++ merge function

C++ merge function

C++ Container Class The C++ container class


merge is used in list tomerges two sorted linked listsfunction; it is a list-specific efficient operation.

merge is a member function of the container class, used to merge another sorted linked list into the current one.

After merging, the elements of the two linked lists are combined in order, and the current list becomes sorted.

Word meaning: merge means "merge," i.e., to merge two sorted linked lists.


Basic syntax and parameters

Syntax format



void merge(list& other);

void merge(list& other, Compare comp);

Parameter Description

Function description


Example

Example 1: Merge two sorted linked lists

Example

#include

#include

int

main

(

)

{

    std

::

list

<

int

list1

=

{

1

,

3

,

5

,

7

,

9

}

;

    std

::

list

<

int

list2

=

{

2

,

4

,

6

,

8

,

10

}

;

    std

::

cout

<<

"list1: "

;

   

for

(

int

n

:

list1

)

std

::

cout

<<

n

<<

" "

;

    std

::

cout

<<

std

::

endl

;

    std

::

cout

<<

"list2: "

;

   

for

(

int

n

:

list2

)

std

::

cout

<<

n

<<

" "

;

    std

::

cout

<<

std

::

endl

;

   

// Merge

    list1.

merge

(

list2

)

;

    std

::

cout

<<

"After merge list1: "

;

   

for

(

int

n

:

list1

)

std

::

cout

<<

n

<<

" "

;

    std

::

cout

<<

std

::

endl

;

    std

::

cout

<<

"After merge list2 size: "

<<

list2.

size

(

)

<<

std

::

endl

;

   

return

0

;

}

Expected output:

list1: 1 3 5 7 9

list2: 2 4 6 8 10

合并后 list1: 1 2 3 4 5 6 7 8 9 10

合并后 list2 大小: 0

Example 2: list2 is emptied after merging

Example

#include

#include

int

main

(

)

{

    std

::

list

<

int

a

=

{

1

,

5

,

6

}

;

    std

::

list

<

int

b

=

{

2

,

3

,

4

,

7

}

;

    a.

merge

(

b

)

;

    std

::

cout

<<

"After merge: "

;

   

for

(

int

n

:

a

)

std

::

cout

<<

n

<<

" "

;

    std

::

cout

<<

std

::

endl

;

    std

::

cout

<<

"Is b empty: "

<<

(

b.

empty

(

)

?

"Yes"

:

"No"

)

<<

std

::

endl

;

   

return

0

;

}

Expected output:

合并后: 1 2 3 4 5 6 7

b 是否为空: 是


C++ Container Class The C++ container class