I have always been fascinated by pointers. Today I looked at pointer swap arrays. I have very little knowledge and hope it can help everyone.
Using pointers to swap arrays is mainly to save time. There are two ways to swap arrays.
The first is to write a function to pass the array over and then exchange it with swap.
The code is as follows:
#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; }
However, such exchange is only useful in functions, and it is still equivalent to no exchange in the main function, so we have another method
#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; }
There are time functions in the code, readers can run them by themselves to see the time, which should be 0.00
The above example explanation of c++ using pointers to exchange arrays is all the content I share with you. I hope you can give you a reference and I hope you can support me more.