翻轉一個數組(c++實現)


反轉一個數組:

其實STL中的vector有一個reverse函數便可以使用。

#include<iostream>
using namespace std;
int* ReverseArray(int*orig,unsigned short int b)
{
    unsigned short int a=0;
    int swap;
    for(a;a<--b;a++) //increment a and decrement b until they meet eachother
    {
        swap=orig[a];       //put what's in a into swap space
        orig[a]=orig[b];    //put what's in b into a
        orig[b]=swap;       //put what's in the swap (a) into b
    }
    return orig;    //return the new (reversed) string (a pointer to it)
}

int main()
{
    const unsigned short int SIZE=10;
    int ARRAY[SIZE]={1,2,3,4,5,6,7,8,9,10};
    int*arr=ARRAY;
    for(int i=0;i<SIZE;i++)
    {
        cout<<arr[i]<<' ';
    }
    cout << endl;
    arr=ReverseArray(arr,SIZE);
    for(int i=0;i<SIZE;i++)
    {
        cout<<arr[i]<<' ';
    }
    cout<< endl;

    return 0;
}

結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM