Home >Backend Development >C++ >Detailed explanation and example demonstration of C++sort function

Detailed explanation and example demonstration of C++sort function

PHPz
PHPzOriginal
2024-04-02 18:39:011424browse

Summary: The C sort function is used to sort container elements. By default, it sorts in ascending order using the

Detailed explanation and example demonstration of C++sort function

C Detailed explanation and example demonstration of sort function

sort function overview

sort function is a powerful function in the C Standard Template Library (STL) for sorting container elements. It arranges the elements in a container into ascending or descending order based on specified comparison rules.

The function is declared as follows:

template<typename Iter>
void sort(Iter first, Iter last);

Among them:

  • Iter: Iterator type pointing to the container element, which can be moved and accessed in the container element.
  • first: Container start iterator, specifying the first element of the range of elements to be sorted.
  • last: Container end iterator, specifying the elements after the last element of the range of elements to be sorted.

Custom comparison rules

By default, the sort function uses the operator for comparison, which means it will Container elements are sorted in ascending order. If you wish to sort according to different rules, you can provide a custom comparison function:

bool compare(const Type1& a, const Type2& b)
{
    // 自定义比较规则
}

// 在 sort 函数中使用自定义比较函数
sort(first, last, compare);

Practical case

Example 1: Sorting an array of integers

#include <iostream>
#include <algorithm>

using namespace std;

int main()
{
    int arr[] = {5, 2, 7, 1, 3};
    int len = sizeof(arr) / sizeof(arr[0]);

    sort(arr, arr + len);

    cout << "排序后的数组:";
    for (int i = 0; i < len; i++)
    {
        cout << " " << arr[i];
    }
    cout << endl;

    return 0;
}

Output:

排序后的数组: 1 2 3 5 7

Example 2: Sorting an array of strings

#include <iostream>
#include <algorithm>

using namespace std;

int main()
{
    string arr[] = {"apple", "orange", "banana", "kiwi", "mango"};
    int len = sizeof(arr) / sizeof(arr[0]);

    sort(arr, arr + len);

    cout << "排序后的数组:";
    for (int i = 0; i < len; i++)
    {
        cout << " " << arr[i];
    }
    cout << endl;

    return 0;
}

Output:

排序后的数组: apple banana kiwi mango orange

The above is the detailed content of Detailed explanation and example demonstration of C++sort function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn