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

C++ sort function

C++ sort function

C++ Container Class The C++ container class


sort is used in list tosorts the linked listfunction; it is a list-specific efficient operation.

sort is a member function of the container class, used to sort the elements in the linked list.

list's sort uses merge sort, with a time complexity of O(n log n), and does not move elements.

Word meaning: sort means "sort," i.e., to sort the elements.


Basic syntax and parameters

Syntax format



void sort();

void sort(Compare comp);

Parameter Description

Function description


Example

Example 1: Basic sorting

Example

#include

#include

int

main

(

)

{

    std

::

list

<

int

numbers

=

{

5

,

2

,

8

,

1

,

9

,

3

}

;

    std

::

cout

<<

"Before sorting: "

;

   

for

(

int

n

:

numbers

)

std

::

cout

<<

n

<<

" "

;

    std

::

cout

<<

std

::

endl

;

    numbers.

sort

(

)

;

    std

::

cout

<<

"After sorting: "

;

   

for

(

int

n

:

numbers

)

std

::

cout

<<

n

<<

" "

;

    std

::

cout

<<

std

::

endl

;

   

return

0

;

}

Expected output:

排序前: 5 2 8 1 9 3

排序后: 1 2 3 5 8 9

Example 2: Descending sort

Example

#include

#include

int

main

(

)

{

    std

::

list

<

int

numbers

=

{

5

,

2

,

8

,

1

,

9

,

3

}

;

   

// Sort in descending order

    numbers.

sort

(

std

::

greater

<

int

(

)

)

;

    std

::

cout

<<

"After descending sort: "

;

   

for

(

int

n

:

numbers

)

std

::

cout

<<

n

<<

" "

;

    std

::

cout

<<

std

::

endl

;

   

return

0

;

}

Expected output:

降序排序后: 9 8 5 3 2 1


C++ Container Class The C++ container class