关于算法之查找和模板
2014-09-02 22:09
148 查看
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;
}
思考:数组与指针操作之“+”
凡是函数体相同的函数都可以用这个模板来代替,不必定义多个函数,只需在模板中定义一次即可。在调用函数时系统会根据实参的类型来取代模板中的虚拟类型,从而实现了不同函数的功能。
// 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;
}
思考:数组与指针操作之“+”
相关文章推荐
- 一个关于汉字查找的算法的猜想
- 【智能查询】:关于智能查找输入的算法实现1
- Java学习之数组1(1.数组的声明;2.元素为引用数据类型的数组;3.关于main方法里的String[] args;4.数组排序;5.数3退1 数组算法,(用数组模拟链表);6数组查找之二分法;7数组的拷贝)
- 关于有序二维矩阵查找和字符串替换的两道算法题
- 关于最短路的几种算法的模板总结
- 关于Prime算法的从入门到升天的讲解(带模板)
- 关于两幅图中相位查找的算法
- php关于二分查找的算法
- 我的第一篇IT博文:关于查找“吸血鬼数字”算法的讨论
- 算法--有关于数组查找—1
- 关于算法--蛮力法--穷举查找法
- 关于二叉树的算法集合
- 关于cnblogs 的KJC模板个性化定制
- 关于猫和老鼠的算法
- 关于算法.
- 关于R-D 优化算法
- 关于平方根运算的算法
- 简单常识——关于 STL 算法
- 关于分解质因数的一个算法
- 关于C++模板的连接问题