C++ <list> sort Function

C++ container class <list>


sortis used in list forSort the linked listThe function is an efficient operation unique to linked lists.

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

list'ssortIt uses merge sort, with a time complexity of O(n log n), and does not cause element movement.

Word Definitions: sortIt means "sort", i.e., sorting the elements.


Basic syntax and parameters

Syntax format

void sort();
void sort(Compare comp);

Parameter description

  • Parameter(Optional):comp- Comparison function

Function description

  • Return Value: void(No return value).
  • Effect: sorting the elements in the linked list.

Example

Example 1: Basic Sorting

Example

#include <iostream>
#include <list>

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 Sorting

Example

#include <iostream>
#include <list>

int main() {
    std::list<int> numbers = {5, 2, 8, 1, 9, 3};

    // Sort in descending order
    numbers.sort(std::greater<int>());

    std::cout << "After sorting in descending order: ";
    for(int n : numbers) std::cout << n << " ";
    std::cout << std::endl;

    return 0;
}

Expected output:

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

C++ container class <list>

other extensions