天天看點

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