C++中排序和数组翻转函数

通过代码及运行结果更有助于理解函数的使用,同时代码中注有详细的注释。

写在前面:函数reverse()和函数sort()都包含在头文件algorithm.h中

1、代码(附超级详细注释)
#include<iostream>
#include<algorithm>

using namespace std;


bool Comp(const int &a,const int &b)//sort函数默认是升序排序,可以通过重写排序比较函数进行降序排序
{
    return a>b;
}
int main()
{
    int str[10] = {2,5,1,9,0};

    reverse(str,str+5);  //翻转数组值
    cout<<"翻转数组:";
    for(int i=0; i<5; i++)
        cout<<str[i]<<" ";
    cout<<endl;

    sort(str,str+5);   //默认的升序排序
    cout<<"升序:";
    for(int i=0; i<5; i++)
        cout<<str[i]<<" ";
    cout<<endl;

    sort(str,str+5,Comp);  //重写之后的降序排序
    cout<<"降序:";
    for(int i=0; i<5; i++)
        cout<<str[i]<<" ";
    cout<<endl;
    return 0;
}


2、运行结果
翻转数组:0 9 1 5 2
升序:0 1 2 5 9
降序:9 5 2 1 0
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值