C++ sort() function

Functions in C++ sort()are standard library functions for sorting elements in containers such as arrays, vectors, linked lists, etc. It uses a sorting algorithm called quicksort, which generally has better performance.

sort()The function is located <algorithm>in the header file and accepts two iterators as parameters representing the range of elements to sort. vector<int> numsFor example, if you want to sort a vector of integers , you can call sort()the function like this:

#include <algorithm>
#include <vector>

int main() {
    std::vector<int> nums = {4, 2, 8, 5, 1};
    std::sort(nums.begin(), nums.end());
    // 现在nums中的元素已经按升序排列
    return 0;
}

sort()The function sorts in ascending order by default. If you need to sort in descending order, you can use greaterthe function object as the third parameter to pass to sort()the function. For example:

#include <algorithm>
#include <functional>
#include <vector>

int main() {
    std::vector<int> nums = {4, 2, 8, 5, 1};
    std::sort(nums.begin(), nums.end(), std::greater<int>());
    // 现在nums中的元素已经按降序排列
    return 0;
}

In addition, sort()the function can also accept a callable object (function or function object) as the third parameter, which is used to customize the way of sorting. With custom comparison functions, you can sort elements according to specific sorting criteria.

It should be noted that sort()the function sorts the elements in the container in-place, that is, it does not create a new container, but directly modifies the order of elements in the original container. Also, sort()the time complexity of the function is usually O(NlogN), where N is the number of elements to be sorted.

To sum up, the C++ sort()function is a very convenient function for sorting container elements. It can easily sort arrays, vectors, etc. in ascending or descending order, and can also implement specific sorting criteria through custom comparison functions.

Guess you like

Origin blog.csdn.net/2201_75772333/article/details/130701805