关于算法之查找和模板

本文介绍了 C++ 中函数模板的概念及其使用方法。通过具体的代码示例,展示了如何利用函数模板减少代码重复,并提高代码的复用性和泛型编程的能力。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C++提供了函数模板(function template)。所谓函数模板,实际上是建立一个通用函数,其函数类型和形参类型不具体指定,用一个虚拟的类型来代表。这个通用函数就称为函数模板

凡是函数体相同的函数都可以用这个模板来代替,不必定义多个函数,只需在模板中定义一次即可。在调用函数时系统会根据实参的类型来取代模板中的虚拟类型,从而实现了不同函数的功能。


// 1.cpp : 定义控制台应用程序的入口点。
//




//


#include "stdafx.h"
#include "stdlib.h"
#include <Windows.h>


#include "assert.h"






int find(int array[], int length, int value)
{
//参数判断
if(NULL == array || 0 == length)
return FALSE;
int index = 0;


for (; index < length; index++)
{
if (array[index] == value)
{
return index;
}
}
return FALSE;
}




template<typename type>
int find1(type array[], int length, type value)
{
if (0 ==length || NULL == array)
{
return FALSE;
}
type *start = array;
type *end = array+length;
while(start < end)
{
if (value == *start)
{
return (((int)start-(int)array)/sizeof(type));
}
start++;
}
return FALSE;
}
static void test1()
{
int array[10] = {1,2};
assert(0 == find(array, 10, 1));
assert(FALSE == find(array, 10, 10));
}


int _tmain(int argc, _TCHAR* argv[])
{
test1();
return 0;
}





思考:数组与指针操作之“+”


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值