STL之find函数讲解

函数声明:


template<class InputIterator, class T> inline

InputIterator find(
			InputIteratorFirst,	//起始查找位置
			InputIteratorLast,	//终止查找位置
			const T&Value		//待查找的值
			)

这个函数就是在Iterators range内执行线性查找.如果找到一个适合的值,则返回该值的一个迭代器.否则返回终止查找位置的迭代器.

一个简单的例子:

vector<string> vecStr;
	vecStr.push_back( "我" );
	vecStr.push_back( "是" );
	vecStr.push_back( "一" );
	vecStr.push_back( "滴" );
	vecStr.push_back( "远" );
	vecStr.push_back( "方" );
	vecStr.push_back( "孤" );
	vecStr.push_back( "心" );

	vector<string>::iterator iterFind = find( vecStr.begin(),vecStr.end(),"方" );
	if ( iterFind != vecStr.end() )
	{
		cout<<"value = "<<*iterFind<<endl;
	}
	else
	{
		cout<<"在vecStr.begin()-----vecStr.end()范围内没有查找到相关记录"<<endl;
	}
	system( "pause" );

这个例子很简单,vector里面的是一个string("内置"类型),所谓内置内型可以理解成,编译器能够比较大小的原子类型.

其实在实际中用到上述内置类型很少.主要是一些自定义的类型,自定义的类型.(C++里面也可以说是类).

使用find时需要注意的问题是,必须要重载==运算符.

具体例子如下:

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

using namespace std;

struct A
{
	string strID;
	int		i;
	A( string strID,int i )
	{
		this->strID = strID;
		this->i     = i;
	}
	bool operator==( const A& a )
	{
		if ( a.strID == strID )
		{
			return true;
		}
		return false;
	}
	
};
typedef vector<A>::iterator vecIter;
inline bool operator< ( const A& usrOne,const A& usrTwo )
{
	if ( usrOne.strID < usrTwo.strID  )
	{
		return true;
	}
	return false;
}
bool cpmVec( A a1,A a2 )
{
	return a1.i > a2.i;
}
void main()
{	
	A a( "1",1 );
	vector<A> vecA;
	
	vecA.push_back( a );

	a.i = 2;
	a.strID = "2";
	vecA.push_back( a );

	a.i = 5;
	a.strID = "2";
	vecA.push_back( a );

	a.i = 4;
	a.strID = "1";
	vecA.push_back( a );

	a.i = 7;
	a.strID = "1";
	vecA.push_back( a );

	a.i = 9;
	a.strID = "1";
	vecA.push_back( a );

	stable_sort( vecA.begin(),vecA.end(),cpmVec );
	for ( vector<A>::iterator iterA = vecA.begin();iterA != vecA.end();iterA ++ )
	{
		cout<<"i = "<<iterA->i<<"strID = "<<iterA->strID<<endl;
	}

	a.strID = "1";
	a.i = 100;
	vecIter iterFind = find( vecA.begin(),vecA.end(),a );
	cout<<"i = "<<iterFind->i<<"strID = "<<iterFind->strID<<endl;

	system( "pause" );
}

,这个函数搞定.




   

你可能感兴趣的:(STL之find函数讲解)