Summary of sort function in C++

  We all know that the sort function is a library function in the C++ standard library <algorithm>. Its function is to sort the elements in an array/container. Usage examples are as follows:

1. Sort the array

Example:

    int a[] = {1,3,7,2};
    sort(a,a + 4);

In this case (that is, by default), the array a is actually sorted in ascending order. We can also modify the content of the third parameter in the sort function to implement custom sorting.

Example:

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

    int a[] = {1,3,7,2};
    sort(a,a + 4,cmp);
}

By customizing the cmp function, the array a is sorted in descending order. Of course, other complex types of data such as structures and classes can also be sorted, but the content of cmp is often rewritten.

2. Sort the container (take vector as an example)

Example:

vector<int> a = {1,3,7,2};
 sort(a.begin(),a.end());

Similar to array sorting, except that the parameters of the function are different. Descending sort is implemented as before.

3. Matters needing attention

  If the sort function is to be called by a member function in the class and a custom cmp function is used, the cmp function must be a static function or a global one.

Example:

class test {
    static bool cmp(int a,int b)
    {
        return a > b;
    }

public:
    void fun(vector<int>& a)
    {
        sort(a.begin(),a.end(),cmp);
    }
};

The comparison function compare in sort should be declared as a static member function or global function, not as a normal member function, otherwise an error will be reported. This is because: non-static member functions depend on specific objects, and functions such as std::sort are global, so non-static member functions cannot be called in sort. Static member functions or global functions are independent of specific objects and can be accessed independently without creating any object instance. At the same time, static member functions cannot call non-static members of the class.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325163649&siteId=291194637