如何使用指针改变数组中元素的顺序

How to change the order of elements in an array using a pointer?

本文关键字:元素 顺序 数组 何使用 指针 改变      更新时间:2023-10-16

例如,我有一个数组:

int Arr[10]={1,2,3,4,5,6,7,8,9,10};

如何使用指针改变其元素的顺序来接收以下数组:

Arr={10,9,8,7,6,5,4,3,2,1}
to change the order odd and even using a pointer I've found this:
But I need only to reverse an array (without replacing odd and even)
#include <iostream>
using namespace std;
int main (const int& Argc, const char* Argv[]){
const int Nelem=10;
int Arr[]={1,2,3,4,5,6,7,8,9,10};
int *begAr=&Arr[0];
int *endAr=&Arr[Nelem];
int *itrAr=begAr;
int *tmpValAr=new int(0);
cout<<"Beforet1 2 3 4 5 6 7 8 9 10"<<endl;
while(itrAr<endAr){
*tmpValAr=*itrAr;
*itrAr=*(itrAr+1);
*(itrAr+1)=*tmpValAr;
itrAr+=2;
}
cout<<"Aftert";
for(int i=0; i<Nelem; ++i)cout<<Arr[i]<<" ";
cout<<endl;
system("pause");
return 0;
}  

好的,c风格的方法使用指针反转数组?这应该不难算。这里有一个方法:

int main ( void )
{
    int i,//temp var
        arr[10]= {1,2,3,4,5,6,7,8,9,10};//the array
    int *start = &arr[0],//pointer to the start of the array
        *end = &arr[9];//pointer to the last elem in array
    //print out current arr values
    for (i=0;i<10;++i)
        printf("arr[%d] = %dn", i, arr[i]);
    do
    {//simple loop
        i = *start;//assign whatever start points to to i
        *start = *end;//assign value of *end to *start
        *end = i;//assign initial value of *start (stored in i) to *end
    } while ( ++start < --end);//make sure start is < end, increment start and decrement end
    //check output:
    for (i=0;i<10;++i)
        printf("arr[%d] = %dn", i, arr[i]);
    return 0;
}

就像你在这里看到的那样,这很好地反转了数组

使用<algorithm>:

std::reverse(Arr, Arr+10);

它将反转你正在请求的一组数据。

这是该函数的近似实现,如果您想自己编写循环,可以根据需要进行调整:

template <class BidirectionalIterator>
  void reverse (BidirectionalIterator first, BidirectionalIterator last)
{
  while ((first!=last)&&(first!=--last)) {
    std::iter_swap (first,last);
    ++first;
  }
}

如果你使用的是C语言,或者想要一个不那么通用的解决方案,可以这样做:

int i = 0; j = 9;
for(;i<j;++i;--j) {
  int tmp = arr[i];
  arr[i] = arr[j];
  arr[j] = arr[i];
}

取两个指针begAr指向arr[0], endAr指向arr[9]。从两边遍历数组,将*begAr*endAr交换,直到begAr > endAr

int tempValAr;
while(endAr >= begAr )
{
    tempValAr = *begAr;
    *begAr++ = *endAr;
    *endAr-- = tempValAr;
}

查看测试程序