码迷,mamicode.com
首页 > 其他好文 > 详细

编写一个模版函数count

时间:2017-08-30 14:09:50      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:return   答案   拷贝   代码   pac   使用   cout   个数   传递   

返回值是数组的a[0:n-1]的数组个数。

知识点:数组的两个特殊性质对我们定义和使用作用在数组上的函数有影响,这两个性质分别是:不允许拷贝数组以及使用数组时(通常)会将其转换成指针。因为不能拷贝数组,所以我们无法以值传递的方式使用数组参数。因为数组会被转换成指针,所以当我们为函数传递一个数组时,实际上传递的饰指向数组首元素的指针。

ex:

void print(const int*);

void print(const int[]);

void print(const int[10])

 

答案:

template <class T>
T count(const T *beg,const T *end)
{
    int n = 0;
    while (beg != end)
    {
        *beg++;
        n++;
    }
    return n;
}

能运行代码如下:

#include <iostream>

using namespace std;

int count(const int *beg, const int *end)
{
	int n = 0;
	while (beg != end)
	{
		*beg++;
		n++;
	}
	return n;
}

int main()
{
	int a[] = { 1,2,3,4 };
	cout << count(begin(a), end(a)) << endl;
	return 0;
}

  

编写一个模版函数count

标签:return   答案   拷贝   代码   pac   使用   cout   个数   传递   

原文地址:http://www.cnblogs.com/drgon/p/7452614.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!