// find_Function.cpp : 定义控制台应用程序的入口点。
//VS 2005
#include "stdafx.h"
#include <vector>
#include <string>
#include <iostream>
using namespace std;
//find 函数
template<class In, class T>
In MyFind(In first, In last, const T& v) //标准
{
while(first != last && *first != v) ++first;
return first;
}
//然而,在传first、last参数时,容易犯错,比如:传不同的容器对象的指针
//于是又了下列的扩充版本
template<class In>
struct Iseq : public pair<In,In>
{
//Iseq(In i1, In i2) : first(i1),second(i2){} //此语句编译不过
Iseq(In i1, In i2) :pair<In,In>(i1,i2)
{
}
};
template<class In, class T>
In MyFind(Iseq<In> r, const T& v) //扩充
{
return MyFind(r.first,r.second,v);
}
//上面的扩充版本写法更复杂,于是有了下面的版本
template <class T>
Iseq<typename T::iterator> iseq(/*const*/ T& t) //不能用const, 带const与不带const算是不同的函数(重载),标准库的实现一般都const版和非const版
{
//return Iseq(t.begin(),t.end()); //写法错误 Iseq<typename T::iterator> 才是类型
return Iseq<typename T::iterator>(t.begin(), t.end());
}
int _tmain(int argc, _TCHAR* argv[])
{
vector<string> strVec;
strVec.push_back("shenzhen");
strVec.push_back("guangzhou");
strVec.push_back("shanghai");
strVec.push_back("beijing");
typedef vector<string>::const_iterator CONST_ITERATOR;
CONST_ITERATOR cItor;
//标准版
cItor = MyFind(strVec.begin(),strVec.end(),"shanghai");
if(cItor != strVec.end())
cout << "find shanghai" << endl;
else
cout << "cannot find shanghai" << endl;
//这样写比标准版的MyFind更麻烦,于是又有了另一个版本
cItor = MyFind(Iseq<CONST_ITERATOR>(strVec.begin(),strVec.end()),"guangzhou");
if(cItor != strVec.end())
cout << "find guangzhou" << endl;
else
cout << "cannot find guangzhou" << endl;
//精简版
cItor = MyFind(iseq(strVec),"shenzhen");
if(cItor != strVec.end())
cout << "find shenzhen" << endl;
else
cout << "cannot find shenzhen" << endl;
system("pause");
return 0;
}
find函数学习与应用
最新推荐文章于 2022-09-27 21:25:53 发布