欢迎访问宙启技术站
智能推送

sort函数详细解析

发布时间:2023-06-21 11:17:40

sort函数是C++中的一个函数,可以对数组进行排序。它可以对数组进行升序排列或者降序排列,也可以自定义排序规则。

sort函数的语法:

sort(first, last);

其中,first表示要排序的数组的首地址,last表示要排序的数组的尾地址。

sort函数的默认排序规则是升序排列,即从小到大排列。

下面我们将详细解析sort函数。

### 一、简单用法

#### 1.1 升序排列

#include <iostream>
#include <algorithm>

using namespace std;

int main()
{
    int a[] = {3, 1, 2};
    sort(a, a+3);
    for(int i=0; i<3; i++)
    {
        cout << a[i] << " ";
    }
    return 0;
}

输出:

1 2 3

#### 1.2 降序排列

#include <iostream>
#include <algorithm>

using namespace std;

bool cmp(int x, int y)
{
    return x > y;
}

int main()
{
    int a[] = {3, 1, 2};
    sort(a, a+3, cmp);
    for(int i=0; i<3; i++)
    {
        cout << a[i] << " ";
    }
    return 0;
}

输出:

3 2 1

在这个示例中,我们定义了一个新的函数cmp,它接受两个整数参数xy,并返回一个bool类型的值。如果x>y,则返回true,否则返回false

在调用sort函数时,我们把这个函数作为第三个参数传入,这样就可以实现降序排序了。

### 二、自定义排序规则

sort函数还可以通过自定义排序规则来对数组进行排序。这在一些需要特定排序规则的场合非常有用。

#### 2.1 字符串排序

#include <iostream>
#include <algorithm>
#include <string>

using namespace std;

bool cmp(string x, string y)
{
    return x<y;
}

int main()
{
    string a[] = {"bbb", "aaa", "ccc"};
    sort(a, a+3, cmp);
    for(int i=0; i<3; i++)
    {
        cout << a[i] << " ";
    }
    return 0;
}

输出:

aaa bbb ccc

在这个示例中,我们定义了一个新的函数cmp,它接受两个字符串参数xy,并返回一个bool类型的值。如果x<y,则返回true,否则返回false

在调用sort函数时,我们把这个函数作为第三个参数传入,这样就可以实现字符串升序排序了。

#### 2.2 结构体排序

#include <iostream>
#include <algorithm>
#include <string>

using namespace std;

struct Student
{
    string name;
    int age;
};

bool cmp(Student a, Student b)
{
    return a.age < b.age;
}

int main()
{
    Student a[] = {{"Tom", 20}, {"Jerry", 18}, {"Bob", 23}};
    sort(a, a+3, cmp);
    for(int i=0; i<3; i++)
    {
        cout << a[i].name << " " << a[i].age << endl;
    }
    return 0;
}

输出:

Jerry 18
Tom 20
Bob 23

在这个示例中,我们定义了一个结构体Student,它包含一个字符串成员name和一个整数成员age

我们还定义了一个新的函数cmp,它接受两个Student类型的参数ab,并返回一个bool类型的值。如果a.age<b.age,则返回true,否则返回false

在调用sort函数时,我们把这个函数作为第三个参数传入,这样就可以实现按照年龄对结构体进行排序了。

### 三、在STL中的应用

sort函数是STL中非常重要的一个函数,它不仅是C++的常用排序函数,也是STL中很多其他算法的基础函数之一。

例如,在下面的代码中,我们使用了一个vectorsort函数来实现对整个序列的排序:

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

int main()
{
    vector<int> a = {3, 1, 2};
    sort(a.begin(), a.end());
    for(int i=0; i<a.size(); i++)
    {
        cout << a[i] << " ";
    }
    return 0;
}

输出:

1 2 3

在这个示例中,我们使用了一个vector来存储整数序列,然后使用sort函数对它进行升序排序。

需要注意的是,我们并没有使用上面介绍的sort(a, a+3);这种形式,而是使用了另一种形式:

sort(a.begin(), a.end());

这个形式表示将sort函数应用于序列的首元素和尾元素之间的所有元素。这个形式是STL中很多其他函数的基础形式,所以熟悉它的用法会让我们在学习其他STL算法时更加容易理解。

此外,sort函数还可以与其他STL算法一起使用,例如使用unique函数删除重复的元素,在这里不再赘述。

### 四、总结

sort函数是C++中的一个重要的排序函数,可以对各种类型的数据进行排序,而且非常灵活,可以根据需要自定义排序规则。

在STL中,sort函数是很多其他算法的基础函数之一,学习sort函数的用法有助于我们更好地理解STL算法库中的其他算法。