How to use the sort function in C++

In C++, the sort function is used to sort the elements in a container, and its usage is as follows:

  1. Include the header file: #include
  2. Specify the container to be sorted, such as an array, vector, or string.
  3. Call the sort function: sort(first, last), where first and last are the beginning and ending iterators of the container, respectively.
  4. The sort function will arrange the elements in the container in ascending order by default. To sort in descending order, a custom comparison function is needed.

For example, the sample code for sorting an integer array in ascending order is as follows:

#include<algorithm>
#include<iostream>

int main() {
    int arr[] = {5, 2, 8, 4, 1};
    int n = sizeof(arr) / sizeof(arr[0]);

    std::sort(arr, arr + n);

    for(int i = 0; i < n; i++) {
        std::cout << arr[i] << " ";
    }

    return 0;
}

The output will be: 1 2 4 5 8

If you want to sort in descending order, you will need to customize a comparison function and pass it as the third parameter to the sort function.

For example, here is a sample code for sorting an integer array in descending order:

#include<algorithm>
#include<iostream>

bool compare(int a, int b) {
    return a > b;
}

int main() {
    int arr[] = {5, 2, 8, 4, 1};
    int n = sizeof(arr) / sizeof(arr[0]);

    std::sort(arr, arr + n, compare);

    for(int i = 0; i < n; i++) {
        std::cout << arr[i] << " ";
    }

    return 0;
}

The output of the result is 8 5 4 2 1.

bannerAds