Example of c++ using Pointers to swap arrays

  • 2020-06-01 10:32:14
  • OfStack

For pointer 1 straight very confusing, today looked at 1 pointer swap array, knowledge is very little, hope to help you.

The main reason to swap arrays with Pointers is to save time. There are two ways to do this

The first is to write a function and pass the array over and swap 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;
}

But this swap is only useful in the function, it's still equivalent to no swap in the main function, so we have another way to do it


#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, so the reader can run 1 to see the time, so it should be 0.00


Related articles: