这篇文章主要介绍c++如何使用指针交换数组,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
利用指针来交换数组主要是为了节省时间嘛,有两种交换方式
第一种是写一个函数把数组传过去然后用swap交换,即可
代码如下:
#include<iostream>
#include<cstdio>
#include<ctime>
using namespace std;
int a[100000050],b[100000050];
void da(int *a,int *b)
{
swap(a,b);
cout<<a[1]<<" "<<b[1]<<endl;
}
int main()
{
double tmp=clock();
a[1]=1,b[1]=2;
da(a,b);
printf("%.2lf",(double)((clock()-tmp)/CLOCKS_PER_SEC));
return 0;
}
但是这样的交换只在函数里有用,到主函数里还是相当于没有交换,所以我们还有另一种方法
#include<iostream>
#include<cstdio>
#include<ctime>
using namespace std;
int a[100000050],b[100000050];
int main()
{
double tmp=clock();
a[1]=1,b[1]=2;
int *op1=a;
int *op2=b;
swap(op1,op2);
cout<<op1[1]<<" "<<op2[1]<<endl;
printf("%.2lf",(double)((clock()-tmp)/CLOCKS_PER_SEC));
return 0;
}
代码里都有时间函数,读者可以自己运行一下看看时间,应该是0.00
以上是“c++如何使用指针交换数组”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注天达云行业资讯频道!