sort函数和next_permutation()函数的用法。

1:sort函数:

sort函数用于C++中,对给定区间所有元素进行排序,默认为升序,

也可进行降序排序。sort函数进行排序的时间复杂度为n*log2n,
比冒泡之类的排序算法效率要高,sort函数包含在头文件为#include<algorithm>的c++标准库中

语法:sort(start,end,compare)

在不写compare参数时,该函数默认为升序排列;

如:

 

#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
    int A[10]={1,2,5,8,9,5,84,2,2,96};
    sort(A,A+10);
    for(int i=0;i<10;i++)
    {
        cout<<A[i]<<" ";
    }
    return 0;
}``

 

运行结果:

 

当然sort函数也可以进行降序排列,不过我们要自己写一个bool的compare函数:

 

#include<iostream>
#include<algorithm>
using namespace std;
bool compare(int x,int y)
{
    return x>y;    
}
int main()
{
    int A[10]={1,2,5,8,9,5,84,2,2,96};
    sort(A,A+10,compare);
    for(int i=0;i<10;i++)
    {
        cout<<A[i]<<" ";
    }
    return 0;
}

 

 这样就可以得到降序排列的数了:

 2:next_permutation()函数的用法:

next_permutation()函数是用来求一个数组的全排列;该函数也是#include<algorithm>中的函数;用起来比较方便;

不用我们自己去写函数了:

具体用法如下:

 

#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
    int  A[]={1,2,3,4};
     do
     {
         for(int i=0;i<4;i++) cout<<A[i];
         cout<<endl;
     }while(next_permutation(A,A+4));
     return 0;
}

 

输出结果:

 这儿有一个比较典型的例子,大家可以去运用运用:https://www.luogu.org/problemnew/show/P1012

AC代码:

#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
int main()
{
    int n;
    cin>>n;
    string A[21];
    for(int i=1;i<=n;i++)
    {
        cin>>A[i];
    }
    string max="0";
    do
    {
        string sum="";
        for(int i=1;i<=n;i++) 
        {
            sum+=A[i];
        }
        if(sum>max) max=sum; 
    }while(next_permutation(A+1,A+n+1));
    cout<<max;
    return 0;
}

 这个题还有另一种解法:就是我们运用字符串可以加减,还有就是数字字符串可以比较大小来做;

AC代码:

#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
using namespace std;
int main()
{
    int n;
    cin>>n;
    string A[21];
    for(int i=1;i<=n;i++)
    {
        cin>>A[i];
    }
    
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=n;j++)
        {
            if(A[j]+A[j+1]<A[j+1]+A[j])//比较两种加和的方式看那种使结果较大。
            swap(A[j],A[j+1]); 
        }
    }
    for(int i=1;i<=n;i++)
    {
        cout<<A[i];
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/zhoubo123/p/11181294.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值