学习杂记六:形参如何获取数组长度

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 <class Type,int size>

  Type min(const Type (&Array)[size]){}//size用来接收数组的长度--元素个数

以下用函数模板来实现希尔排序:

#include<iostream>
using namespace std;

template <class Type, int size>
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 << a[i] << "  ";
	}
	delete[]a;
}

int main()
{
	const int a[10] = { 49,38,65,97,76,13,27,49,55,04 };
	cout << "希尔排序:" << endl;
	xier(a);
	
	system("pause");
}

若想希尔函数与main函数不在同一个文件中,可将希尔函数放在头文件中

若想将希尔函数放在另一个cpp文件中,据说要在main.cpp中声明

export template <class Type, int size>
void xier(const Type(&Array)[size]);

但是我不知道怎么引入关键字export(哭惹)

 

解决方案来源:https://bbs.csdn.net/topics/190176995

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值