下面小编就为大家分享一篇c++用指针交换数组的实例讲解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
对于指针一直很迷,今天看了一下指针交换数组,知识量很少,希望能帮助到大家。
利用指针来交换数组主要是为了节省时间嘛,有两种交换方式
第一种是写一个函数把数组传过去然后用swap交换,即可
代码如下:
#include #include #include using namespace std; int a[100000050],b[100000050]; void da(int *a,int *b) { swap(a,b); cout<</div><p><span style="color: #ff00ff"><strong>但是这样的交换只在函数里有用,到主函数里还是相当于没有交换,所以我们还有另一种方法</strong></span></p><div class="gaodaimacode"><pre class="prettyprint linenums"> #include #include #include 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("%.<i style="color:transparent">来源gaodai$ma#com搞$代*码网</i>2lf",(double)((clock()-tmp)/CLOCKS_PER_SEC)); return 0; }
代码里都有时间函数,读者可以自己运行一下看看时间,应该是0.00
以上就是c++用指针交换数组的实例讲解的详细内容,更多请关注gaodaima搞代码网其它相关文章!