两种数组传值方法

来源:互联网 发布:python 一段时间日期 编辑:程序博客网 时间:2024/05/17 10:42
#include<iostream>
using namespace std;


template <typename T>
//void sort(T*);
void sort(T&);


int main(){
int a[20] = {1,3,5,7,9,11,13,15,17,19,2,4,6,8,10,12,14,16,18,20};

sort(a);

cout<<"after sort:"<<endl;
for(int i = 0;i<20;i++){
cout<<a[i]<<" ";
}
cout<<endl;
}


/*template <typename T>
void sort(T* a){ //参数是传的指针 
T temp;
cout<<sizeof(a)/sizeof(a[0])<<endl;//这里前面算的是指针a,所以是4/4 = 1; 
for(int i = 0;i<20;i++){//这里用i<sizeof(a)/sizeof(a[0])是得不到正确答案的 
for(int j = i+1;j<20;j++){
if(a[i] > a[j]){
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
}*/


template <typename T>
void sort(T& a){ //这里用引用的方式传值 
int temp;//这里不能用T temp
cout<<sizeof(a)/sizeof(a[0])<<endl;//可以计算出传进来的数组的长度
int len = sizeof(a)/sizeof(a[0]); 
for(int i = 0;i<len;i++){
for(int j = i+1;j<len;j++){
if(a[i] > a[j]){
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
}



原创粉丝点击