栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++ sort函数用法

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++ sort函数用法

个人简单记录一下sort函数的用法,方便下次直接使用

  1. sort包含在头文件中,用于对数组进行排序
  2. sort可以有三个参数,sort(begin,end,cmp),第三个参数可以自己定义排序的规则,从而可以对二维数组进行排序等。
  3. 基本用法
    数组定义:
    vectornums;
  • 默认:sort(nums.begin(),nums.end());
    对nums数组进行升序排序
  • 自定义以进行降序排序
bool cmp(int x, int y) {
    return x > y;
}
sort(nums.begin(),nums.end(),cmp);
  • 对二维数组自定义规则排序
    二维数组:vector>nums;
    例:按照每个子数组中第一个数递减,第二个递增排序
#include 
#include 
#include
using namespace std;
//核心代码
bool cmp(vectorx, vectory){
	return x[0]>y[0]||x[0]==y[0]&&x[1]v){
    cout<>nums={{1,5},{10,4},{4,6}};
    sort(nums.begin(),nums.end(),cmp);
    for_each(nums.begin(),nums.end(),show);
    system("pause");
    return 0;
}

运行结果如下:

*第三个参数也可不在外部额外定义排序规则,可以直接写在括号里,例如

sort(nums.begin(),nums.end(),[&](int x,int y){return x>y});
//或者
sort(nums.begin(),nums.end(),[&](auto& x, auto& y){return x[0]>y[0] || x[0]==y[0] && x[1]
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/290417.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号