例如,我有一个数组:
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<<"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;
}
答案 0 :(得分:2)
使用<algorithm>
中的reverse:
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];
}
答案 1 :(得分:2)
好的,使用指针反转数组的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] = %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;
}
正如您所见here,这可以很好地反转数组。
答案 2 :(得分:1)