// Data structures and Algorithm Analysis in C++
// ex 3-3
#include<iostream>
#include<iterator>
#include<assert.h>
#include<vector>
#include<string>
using namespace std;
template <typename Iterator,typename Object>
Iterator find(Iterator start,Iterator end,const Object& x)
{
Iterator iter = start;
while(iter != end && *iter != x)
{
cout << " *iter = " << *iter << " ; x = " << x << endl;
cout << (*iter == x) << endl;
iter++;
}
return iter;
}
int main()
{
vector<string> vec;
vec.push_back("hello");
vec.push_back("world");
vec.push_back("this ");
vec.push_back("is ");
vec.push_back("c++ ");
string s = "hello ";
vector<string>::iterator iter = find(vec.begin(),vec.end(),s);
//assert(iter!=vec.end());
cout << *iter << endl;
}
notes: 如果不进行判断处理,直接进行cout ,在没有找到的情况下cout会出现“vector iterator not dereferenable”的错误。