等后面学完了再来细写,先备份个代码。
参考:
- 《Essential C++》
#include <iostream>
#include <vector>
#include <list>
using namespace std;
template <typename elemType>
elemType *find_pre_version(const elemType *array, const elemType *sentinel, const elemType &value);
// const情况会导致传入string指针时报错
template <typename IteratorType, typename elemType>
IteratorType find(IteratorType first, IteratorType last, const elemType &value)
{
for (; first != last; ++first)
{
if (*first == value)
{
return first;
}
}
return last;
}
template <typename elemType>
elemType *find_pre_version(elemType *first,elemType *last, const elemType &value)
{
if (!first || !last)
{
return 0;
}
for (; first != last; ++first)
{
if (*first == value)
{
return first;
}
}
return 0;
}
template <typename elemType>
inline elemType *begin(vector<elemType> &vec)
{
return vec.empty() ? 0 : &vec[0];
}
template <typename elemType>
inline elemType *end(vector<elemType> &vec)
{
return vec.empty() ? 0 : &vec[vec.size()];
}
int main()
{
int ia[8] = {1, 2, 3, 4, 5, 6, 7, 8};
double da[8] = {1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5};
string sa[8] = {"a0", "b1", "c2", "d3", "e4", "f5", "g6", "h7"};
int *pi = find(ia, ia + 8, ia[3]);
double *pd = find(da, da + 8, da[3]);
string *ps = find(sa, sa + 8, sa[3]);
cout << "*pi: " << *pi << ", *pd: " << *pd << ", *ps: " << *ps << endl;
vector<int> via(ia, ia + 8);
vector<int>::iterator it;
it = find(via.begin(), via.end(), 5);
if(it != via.end()) {
cout << "*vector_iter: " << *it << endl;
}
int *vpi = find_pre_version(begin<int>(via), end<int>(via), 5);
cout << "*vpi: " << *vpi << endl;
list<int> lia(ia, ia+8);
list<int>::iterator iter;
iter = find(lia.begin(), lia.end(), 5);
if(iter != lia.end()) {
cout << "*list_iter: " << *iter << endl;
}
return 0;
}
输出结果:
*pi: 4, *pd: 2.5, *ps: d3
*vector_iter: 5
*vpi: 5
*list_iter: 5
这篇博客展示了如何使用C++模板函数实现`find`和`find_pre_version`两个查找算法,并在整型数组、双精度浮点型数组和字符串数组中应用。示例代码包括对`vector`和`list`容器的查找操作,最后运行结果验证了算法的正确性。
748

被折叠的 条评论
为什么被折叠?



