如何使用指针改变数组中元素的顺序
How to change the order of elements in an array using a pointer?
例如,我有一个数组:
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;
}
查看测试程序
相关文章:
- 为什么用户定义的函数不按照给定的顺序对相同长度的元素进行排序?
- 快速排序 - 三个中位数枢轴选择 - 某些元素顺序不正确
- 序列容器 - 只能按顺序访问元素
- 如何检查 2 个 c++ 数组在 O(1) 或 O(log n) 时间复杂度中是否相同(所有元素都相同,顺序很重要)?
- 保留从一个多集复制到另一个多集的元素的顺序
- 如何在 C++ 中将从文本文件中读取的元素推送和弹出到数组中,并按 Revserse 顺序输出堆栈?
- 查找数组的第一个和最后一个索引,其中 from 和 to 元素的顺序总和最大
- 编写一个递归功能,该功能采用数组并以相反顺序显示元素,而无需在末尾启动数组的索引
- 编写链接函数的更短/更有效的方法,该函数按字典顺序添加新元素
- stable_sort不遵守元素的顺序
- 从容器中获取随机元素,该容器在恒定时间内没有严格的元素顺序
- 如何在默认和二维数组中找到顺序扩大元素的位置
- 多重映射是否保证广告顺序与其初始值设定项中给出的元素顺序匹配
- 调用std::nth_element后第n个元素之前的元素顺序
- 如何从向量中删除随机元素而不重复它们并保持元素顺序?C++
- 如何在不更改元素顺序的情况下合并两个unordered_maps
- b树实现中的元素顺序错误
- 提升::p tr_向量改变元素顺序
- Equal_range c++元素顺序
- std::unordered_multimap中的元素顺序