函数原型:
template<class InputIterator, class T>
InputIterator find ( InputIterator first, InputIterator last, const T& value )
{
for ( ; first != last ; first++) if ( *first == value ) break;
return first;
}
返回区间 [ first , end ] 中第一个值等于 value 的元素的位置。
如果没有找到匹配元素,则返回 end。
复杂度:线性复杂度。最多比较次数:元素的总个数。
程序实例:
下面的程序在 int 类型的 vector 中搜寻元素 5 和 12,如果搜索到,就返回其位置 , 否则输出提示信息。
Main.cpp:
#include <iostream>
#include <vector>
#include <algorithm> //find 需要
using namespace std ;
template < class T > //模板
inline void INSERT_ELEMENTS( T &col , int first , int last )
{
for( int i = first ; i <= last ; i++ )
col.insert( col.end() , i ) ;
}
int main()
{
vector<int> Ivec ;
INSERT_ELEMENTS( Ivec , 1 , 9 ) ;
vector<int>::iterator pos ; //迭代器
pos = find( Ivec.begin() , Ivec.end() , 5 ) ; //查找5
if( pos == Ivec.end() ) //没找到
cout << " 5 不存在。\n" ;
else {
cout << " 5 存在 , 位置 " <<
distance(Ivec.begin() , pos ) + 1 << endl ;
}
pos = find( Ivec.begin() , Ivec.end() , 12 ) ;
if( pos == Ivec.end() )
cout << " 12 不存在。\n" ;
else {
cout << " 12 存在 , 位置 " <<
distance(Ivec.begin() , pos ) + 1 << endl ;
}
return 0 ;
}
运行结果: