C++ sort function
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
- Parameters(optional):
comp- Comparison function
Function description
- Return Value:
void(No return value). - effect: Sorts the elements in the linked list.
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
The C++ container class