学习杂记六:形参如何获取数组长度 | 您所在的位置:网站首页 › c如何获取数组的长度 › 学习杂记六:形参如何获取数组长度 |
A数组作为参数传递给函数进行排序,但不想改变A数组数据位置,即数组不进行虚实结合 eg:const int A[10] = { 49,38,65,97,76,13,27,49,55,04 }; void(const int a[]) 但是这样就没法子在函数内部用 int len=sizeof(a);获取数组大小,因为C/C++语言中,当数组作为函数的参数时,该参数退化为指针,数组长度信息完全丢失。 解决方案有三: 1、增加第二个参数size_t length,把长度传入第二个参数中。该方法适合C,对于C++则不是很推荐。 2、放弃普通数组,使用vector。函数的参数改成vector &。该方法适用于C++,但无法在C中使用。 3、使用函数模板。该方法适用于C++,但无法在C中使用。 template Type min(const Type (&Array)[size]){}//size用来接收数组的长度--元素个数 以下用函数模板来实现希尔排序: #include using namespace std; template void xier(const Type(&Array)[size]) { int *a = new int[size]; for (int i = 0; i < size; i++) { a[i] = Array[i]; } int i, j, d; int tmp; d = size / 3;//设置增量 while (d > 0)//出口 { for (i = d; i < size; i++)//对所有组采用直接插入排序 { tmp = a[i];//对相隔d个为止一组采用直接插入排序 j = i - d; while (j >= 0 && tmp < a[j]) { a[j + d] = a[j]; j = j - d; } a[j + d] = tmp; } d = d / 2;//减小增量 } for (int i = 0; i < 10; i++) { cout |
CopyRight 2018-2019 实验室设备网 版权所有 |