当前位置: 代码迷 >> 综合 >> 模块和泛型算法(C++沉思录)
  详细解决方案

模块和泛型算法(C++沉思录)

热度:81   发布时间:2024-02-05 09:11:50.0

#include <iostream>
#include <stdio.h>
using namespace std;

/*
关于find使用的数据结构,我们必须知道那些情况呢?
1.我们正在查找某个类型为int的值
2.我们正在一个int对象数组中进行查找
3.我们已经预先知道了数组中的元素的数目
4.我们知道了第一个元素的地址
*/
const int* find1(const int* array, int n, int x)
{
const int*p = array;
for(int i = 0; i < n; i++)
{
if (*p == x)
{
return p;
}
++p;
}

    return 0;
}


/*
* 使用模板去除对int的依赖性
*/
template<class T>
T* find2(T* array, int n, const T& x)
{
T* p = array;
for(int i = 0; i < n; i++)
{
if (*p == x)
{
return p;
}
++p;
}
return 0;
}

/*
* 用!=而不用<来判断循环结束并不是偶然的。从某种角度来说,两者没有区别:如果find3的输入有意义,则p就小于beyond,之道他们相等为止。但是,由<加以总体排序的类型通常也能用!=来进行毕竟。另一方面,考虑一下我们以后可能会用到的用来代替指针的类型,它们可能能够很多地定义!=,,但是不能定义<。此时,使用<就是一个不合理的类型。
*/
template<class T>
T* find3(T* array, T* beyond, const T& x)
{
T* p = array;
///while(p < beyond)
while(p != beyond)
{
if (*p == x)
{
return p;
}
++p;
}
return 0;
}

///这里return beyond,而不是return 0是对通用性的渴望,返回0也是没有问题的
template<class T>
T* find4(T* array, T* beyond, const T& x)
{
T* p = array;
///while(p < beyond)
while(p != beyond)
{
if (*p == x)
{
return p;
}
++p;
}

    return beyond;
}

/*
* 可以把指针当作参数接受,并把它们作为结果返回
* 可以比较指针相等不相等
* 可以解除引用指针,以便得到一个值
* 可以递增指针,以指向下一个元素
*/
template<class P, class T>
P find6(P start, P beyond, const T& x)
{
while (start != beyond && *start != x)
++start;
return start;
}

int main()
{

    return 0;
}


  相关解决方案