C++中的sort函数总结

本文详细介绍了C++标准库中的sort函数,包括其参数说明、使用方法及自定义排序规则。通过实例展示了基本数据类型和结构体的排序,并介绍了容器内元素的排序技巧。

1、sort函数包含在头文件为#include<algorithm>的c++标准库中,调用标准库里的排序方法可以实现对数据的排序,但是sort函数是如何实现的,我们不用考虑!


2、sort函数的模板有三个参数:

void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);
  • 第一个参数first:是要排序的数组的起始地址。

  • 第二个参数last:是结束的地址(最后一个数据的后一个数据的地址)

  • 第三个参数comp是排序的方法:可以是从升序也可是降序。如果第三个参数不写,则默认的排序方法是从小到大排序。


3、实例

#include<iostream>
#include<algorithm>
using namespace std;
main()
{
  //sort函数第三个参数采用默认从小到大
  int a[]={45,12,34,77,90,11,2,4,5,55};
  sort(a,a+10);
  for(int i=0;i<10;i++)
  cout<<a[i]<<" ";
}

运行结果:

在这里插入图片描述


#include<iostream>
#include<algorithm>
using namespace std;
bool cmp(int a,int b);
main(){
  //sort函数第三个参数自己定义,实现从大到小
  int a[]={45,12,34,77,90,11,2,4,5,55};
  sort(a,a+10,cmp);
  for(int i=0;i<10;i++)
    cout<<a[i]<<" ";
}
//自定义函数
bool cmp(int a,int b){
  return a>b;
}

运行结果:

在这里插入图片描述


1 #include<iostream>
 2 #include<algorithm>
 3 #include"cstring"
 4 using namespace std;
 5 typedef struct student{
 6   char name[20];
 7   int math;
 8   int english;
 9 }Student;
10 bool cmp(Student a,Student b);
11 main(){
12   //先按math从小到大排序,math相等,按english从大到小排序 
13   Student a[4]={{"apple",67,89},{"limei",90,56},{"apple",90,99}};
14   sort(a,a+3,cmp);
15   for(int i=0;i<3;i++)    
16   cout<<a[i].name <<" "<<a[i].math <<" "<<a[i].english <<endl;     
17 }
18 bool cmp(Student a,Student b){
19   if(a.math >b.math )
20   return a.math <b.math ;//按math从小到大排序 
21   else if(a.math ==b.math )
22       return a.english>b.english ; //math相等,按endlish从大到小排序23 
24 }

运行结果:

在这里插入图片描述


4.对于容器,容器中的数据类型可以多样化

1) 元素自身包含了比较关系,如int,double等基础类型,可以直接进行比较greater() 递减, less() 递增(省略)

#include<iostream>
#include<algorithm>
#include"vector"
using namespace std;
typedef struct student{
    char  name[20];
    int math;
    int english;
}Student;
bool cmp(Student a,Student b);
main(){
    int s[]={34,56,11,23,45};
    vector<int>arr(s,s+5);
    sort(arr.begin(),arr.end(),greater<int>());
    for(int i=0;i<arr.size();i++)
        cout<<arr[i]<<" ";
}

运行结果:

在这里插入图片描述


2)元素本身为class或者struct,类内部需要重载< 运算符,实现元素的比较;

注意事项:bool operator<(const className & rhs) const; 如何参数为引用,需要加const,这样临时变量可以赋值;重载operator<为常成员函数,可以被常变量调用;

#include<iostream>
#include<algorithm>
#include"vector"
using namespace std;
typedef struct student{
    char  name[20];
    int math;
    //按math从大到小排序
    inline bool operator < (const student &x) const {
        return math>x.math ;
    }
}Student;
main(){
    Student a[4]={{"apple",67},{"limei",90},{"apple",90}};
    sort(a,a+3);
    for(int i=0;i<3;i++)
        cout<<a[i].name <<" "<<a[i].math <<" " <<endl;
}

运行结果:

在这里插入图片描述

<think> 我们正在讨论C++sort函数的使用语法。根据之前的引用和回答,我们可以总结如下: 在C++中,sort函数位于<algorithm>头文件中。它有两种常用的形式: 1. 默认形式(使用operator<进行升序排序): void sort( RandomIt first, RandomIt last ); 2. 带自定义比较函数的形式: void sort( RandomIt first, RandomIt last, Compare comp ); 其中,first和last是随机访问迭代器,表示要排序的范围[first, last)。comp是一个二元谓词(可以是函数指针、函数对象或lambda表达式),用于定义排序规则。 示例代码: #include <algorithm> #include <vector> #include <iostream> int main() { std::vector<int> vec = {4, 2, 5, 1, 3}; // 默认升序排序 std::sort(vec.begin(), vec.end()); // 使用lambda表达式进行降序排序 std::sort(vec.begin(), vec.end(), [](int a, int b) { return a > b; }); // 使用函数对象进行自定义排序 struct { bool operator()(int a, int b) const { return a < b; } } customLess; std::sort(vec.begin(), vec.end(), customLess); return 0; } 注意事项: - sort函数要求迭代器是随机访问的(如vector、deque、原生数组的指针等),不支持关联容器(如map、set)和部分序列容器(如list,list有自身的sort成员函数)。 - 自定义比较函数必须满足严格弱序关系,即: * 非自反:comp(a, a) 为 false * 非对称:若 comp(a, b) 为 true,则 comp(b, a) 为 false * 可传递:若 comp(a, b) 为 true 且 comp(b, c) 为 true,则 comp(a, c) 为 true * 等价传递:若 !comp(a, b) && !comp(b, a) 且 !comp(b, c) && !comp(c, b),则 !comp(a, c) && !comp(c, a) 引用说明: 根据引用[2],sort函数的语法格式为:void sort (RandomAccessIterator first, RandomAccessIterator last); 根据引用[4],我们可以通过自定义比较函数来实现升序或降序排序。 生成相关问题: 1. 在C++中如何对自定义结构体数组使用sort函数进行排序? 2. sort函数在使用自定义比较函数时需要注意哪些规则? 3. C++sort函数的底层实现原理是什么? 4. 如何对容器中的部分元素进行排序? 注意:在回答中,我们引用了文献,所以在末尾添加引用标识。 </think> ### C++ 中 `sort` 函数的使用语法 `sort` 是 C++ 标准库 `<algorithm>` 中的排序函数,语法如下: #### 1. 默认升序排序(无需自定义比较函数) ```cpp #include <algorithm> // 语法 sort(RandomAccessIterator first, RandomAccessIterator last); ``` **参数说明**: - `first`:指向排序范围起始位置的迭代器(如数组首地址) - `last`:指向排序范围**末尾后一位**的迭代器(如数组首地址 + 长度) **示例**: ```cpp int arr[] = {3, 1, 4, 2}; sort(arr, arr + 4); // 升序排序:{1, 2, 3, 4} ``` #### 2. 自定义排序规则 ```cpp // 语法 sort(RandomAccessIterator first, RandomAccessIterator last, Compare comp); ``` **参数说明**: - `comp`:自定义比较函数/函数对象,定义元素间的大小关系 - 函数签名:`bool comp(const Type &a, const Type &b)` - 返回 `true` 时:`a` 应排在 `b` 前面 - 返回 `false` 时:`a` 不强制排在 `b` 前面 **示例**: ```cpp // 降序排序(自定义函数) bool descending(int a, int b) { return a > b; // a > b 时返回 true } sort(arr, arr + 4, descending); // {4, 3, 2, 1} // Lambda 表达式(更简洁) sort(arr, arr + 4, [](int a, int b) { return a > b; }); ``` #### 3. 支持的数据结构 - **原生数组**:`sort(arr, arr + n)` - **容器**(需支持随机访问迭代器): ```cpp vector<int> vec = {3, 1, 4, 2}; sort(vec.begin(), vec.end()); ``` #### ⚠️ 注意事项 1. **迭代器范围**:`[first, last)` 为**左闭右开**区间 2. **时间复杂度**:平均 $O(n \log n)$,基于快速排序实现[^1] 3. **自定义函数的规则**: - 需满足**严格弱序**(如 `a < b` 不可同时有 `b < a`) - 不可修改元素(建议参数为 `const &` 类型) #### 完整示例 ```cpp #include <iostream> #include <algorithm> #include <vector> using namespace std; int main() { vector<int> data = {5, 3, 9, 1, 7}; // 默认升序 sort(data.begin(), data.end()); // 结果:{1, 3, 5, 7, 9} // 自定义降序 sort(data.begin(), data.end(), [](int a, int b) { return a > b; }); // 结果:{9, 7, 5, 3, 1} } ``` > 📌 **关键点**:通过自定义 `comp` 函数,可实现任意复杂度的排序逻辑(如结构体多字段排序、特殊规则排序等)[^4]。 --- ### 相关问题 1. 如何用 `sort` 函数对自定义结构体进行排序? 2. `sort` 函数在处理大规模数据时如何避免性能瓶颈? 3. 什么情况下 `sort` 函数会退化为 $O(n^2)$ 时间复杂度? 4. C++ 的 `sort` 与 C 语言的 `qsort` 有哪些性能差异?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

贝勒里恩

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值