InputIterator find (InputIterator beg, InputIterator end, const T& value);
InputIterator find_if (InputIterator beg, InputIterator end, UnaryPredicate op);
功能:
第一形式返回区间[beg, end)中的第一个“元素值等于value”的元素位置
第二形式返回区间[beg, end)中令一元判断式op(elem)结果为true的第一个元素的位置
a、如果没有找到匹配元素,两种形式都返回end
b、注意op在函数调用过程中不应该改变自身状态
c、op不应该改动传进来的参数
d、如果是已序区间,应使用lower_bound(),upper_bound(),equal_range()或binary_search()算法以获取更高的性能
e、关联式容器(set/multiset,map/multimap)提供了一个等效的成员函数find(),拥有对数时间复杂度
f、时间复杂度:线性
class CPeople
{
int m_nAge;
string m_strName;
public:
CPeople(int nAge= 0) :m_nAge(nAge){}
CPeople(int nAge, string strName):m_nAge(nAge),m_strName(strName){}
int get_age() { return m_nAge; }
string get_name() { return m_strName; }
friend ostream& operator<<(ostream &ouput, CPeople people);
};
ostream & operator<<(ostream &output , CPeople people)
{
output << people.get_name() << " " << people.get_age() << endl;
return output;
}
class CFindName
{
string m_strName;
public:
CFindName(string strName = ""):m_strName(strName)
{
}
bool operator()(CPeople people)
{
if (people.get_name() == m_strName)
return true;
return false;
}
};
int main(int argc, char *argv[])
{
/************find的使用************/
int arr[] = {20,30,20,23,45,80};
vector<int> vec1(arr, arr + sizeof(arr)/sizeof(arr[0]));
vector<int>::const_iterator iterVec1 = find(vec1.begin(),vec1.end(), 80);
if (iterVec1 != vec1.end())
cout << *iterVec1 << endl;
else
cout << "没有找到指定值" << endl;
/************find_if的使用************/
CPeople arrPeople[] = {CPeople(20,"乔峰"),CPeople(15,"段誉"),CPeople(33,"赵敏"),CPeople(80,"虚竹"),CPeople(7,"白眉大侠"),CPeople(18,"周芷若"),CPeople(50,"南慕容")};
vector<CPeople> vec2(arrPeople, arrPeople + sizeof(arrPeople)/sizeof(arrPeople[0]));
vector<CPeople>::const_iterator iterVec2 = find_if(vec2.begin(),vec2.end(), CFindName("虚竹"));
if (iterVec2 != vec2.end())
cout << *iterVec2;
else
cout << "没有找到指定学员的信息" << endl;
return 0;
}