简体   繁体   中英

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

For example, I have an array:

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

How to change its order of elements using a pointer to receive the following array:

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<<"Before\t1 2 3 4 5 6 7 8 9 10"<<endl;
while(itrAr<endAr){
*tmpValAr=*itrAr;
*itrAr=*(itrAr+1);
*(itrAr+1)=*tmpValAr;
itrAr+=2;
}
cout<<"After\t";
for(int i=0; i<Nelem; ++i)cout<<Arr[i]<<" ";
cout<<endl;
system("pause");
return 0;
}  

Use reverse found in <algorithm> :

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

It will reverse a set of data like you are requesting.

This is the approximate implementation of the function, which you could adapt if necessary to your needs if you would like to write the loop yourself:

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

If you are in C or would like a less general solution, do something like this:

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

Ok, a C-style approach using pointers to reverse an array? That shouldn't be too hard to figure out. Here's one approach:

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] = %d\n", 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] = %d\n", i, arr[i]);
    return 0;
}

As you can see here , this reverses the array just fine.

Take two pointers begAr pointing at arr[0] and endAr pointing at arr[9] . Traverse the array from both sides and swap *begAr with *endAr until begAr > endAr .

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

See the test program .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM