学习数据结构与算法,总结与反思。
一个有良好编程规范的代码(转)
template<typename type> <span style="white-space:pre"> </span>//定义模板,使得type代表任意数据类型,但是要保持一致(同int或者同double...)
int find(type array[], int length, type value)
{
if(NULL == array || 0 == length)<span style="white-space:pre"> </span>//做参数合法性检测
return FALSE;
type* start = array;<span style="white-space:pre"> </span>//使用指针可以提高效率
type* end = array + length;
while(start < end){
if(value == *start)<span style="white-space:pre"> </span>
return ((int)start - (int)array)/(sizeof(type)); //强制转化为整型,因为之前是type型
start ++;
}
return FALSE;
}
测试用例
static void test1()<span style="white-space:pre"> </span>//static作用于函数:e.g.: static void func(void);<span lang="EN-US" style="font-size: 10.5pt; font-family: Arial, sans-serif; background-image: initial; background-attachment: initial; background-size: initial; background-origin: initial; background-clip: initial; background-position: initial; background-repeat: initial;"></span>
{
int array[10] = {0};
assert(FALSE == find<int>(NULL, 10, 10));<span style="white-space:pre"> </span>//如果条件错误,停止执行
assert(FALSE == find<int>(array, 0, 10));
}
static void test2()
{
int array[10] = {1, 2};
assert(0 == find<int>(array, 10, 1));
assert(FALSE == find<int>(array, 10, 10));
}