c++用指針交換數組
阿新 • • 發佈:2017-11-25
void cti 方式 沒有 oid urn stream ret 應該 {
double tmp=clock();
a[1]=1,b[1]=2;
da(a,b);
printf("%.2lf",(double)((clock()-tmp)/CLOCKS_PER_SEC));
return 0;
} 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;
}
對於指針一直很迷,今天看了一下指針交換數組,知識量很少,希望能幫助到大家。
利用指針來交換數組主要是為了節省時間嘛,有兩種交換方式
第一種是寫一個函數把數組傳過去然後用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();
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++用指針交換數組