sort()函数

sort()函数
Sort函数有三个参数:
(1)第一个是要排序的数组的起始地址。
(2)第二个是结束的地址(最后一位要排序的地址)
(3)第三个参数是排序的方法,可以是从大到小也可是从小到大,还可以不写第三个参数,此时默认的排序方法是从小到大排序。

Sort函数使用模板:

Sort(start,end,排序方法)
bool cmp(Node start, Node end)
{
return start.c < end.c; //返回值为true时,第一个参数在第二个参数之前
}

sort(p.begin(),p.end(),cmp);
一: 简介

sort函数用于C++中,对给定区间所有元素进行排序,默认为升序,也可进行降序排序。
sort函数进行排序的时间复杂度为n*log2n,快速排序
sort函数包含在头文件为#include“algorithm”的c++标准库中。

二:实例
1.以int为例的基本数据类型的sort使用

#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int main()
{
    int a[5]={1,3,4,2,5};
    sort(a,a+5);
    for(int i=0;i<5;i++)
            cout<<a[i]<<' ';
    return 0;
 }

因为没有cmp参数,默认为非降序排序,结果为:
1 2 3 4 5
若设计为非升序排序,则cmp函数的编写:

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

标准库里有现成的,在functional里,直接用就可以。functional提供了一堆基于模板的比较函数对象。它们是(看名字就知道意思了):equal_to、not_equal_to、greater、greater_equal、less、less_equal。对于这个问题来说,greater和less就足够了,直接拿过来用:

升序:sort(begin,end,less<data-type>());

降序:sort(begin,end,greater<data-type>()).

int  main ( )
{
      int a[20]={2,4,1,23,5,76,0,43,24,65},i;
      for(i=0;i<20;i++)
          cout<<a[i]<<endl;
      sort(a,a+20,greater<int>());
      for(i=0;i<20;i++)
          cout<<a[i]<<endl;
      return 0;
}

二:引用数据类型string的使用
一个字符串间的字符排序:
使用迭代器可以完成顺序排序

#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int main()
{
    string str("hello world");
    sort(str.begin(),str.end());
    cout<<str;
    return 0;
 }

结果:空格dehllloorw

使用反向迭代器可以完成逆序排序

#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int main()
{
    string str("hello world");
    sort(str.rbegin(),str.rend());
    cout<<str;
    return 0;
 }

三:以结构体为例的二级排序

#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
struct link
{
    int a,b;
};
bool cmp(link x,link y)
{
    if(x.a==y.a)
        return x.b>y.b;
    return x.a>y.a;
}
int main()
{
    link x[4];
    for(int i=0;i<4;i++)
        cin>>x[i].a>>x[i].b;
    sort(x,x+4,cmp);
    for(int i=0;i<4;i++)
        cout<<x[i].a<<' '<<x[i].b<<endl;
    return 0;
 }

想对它进行排序:先按a值升序排列,如果a值相同,再按b值降序排列

若是遇到了对结构体中的一个元素进行排序的时候,就得cmp函数来判断:
例:

struct Node {
	int a;
	int b;
	int c;
};
vector<Node>p;

若是针对c排序,然后整体跟着排序:

bool cmp(Node start, Node end)
{
	return start.c < end.c;  //按着耗资来排序 
}

sort(p.begin(),p.end(),cmp);

sort()函数默认的排序方式为升序,如果需要降序排序,可以自定义排序函数

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

对vector 进行排序时

sort(vec.begin(),vec.end(),comp);

这样排序出的vector就是降序

评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值