find算法用于在容器中查找某个指定的值。find算法实现如下:
template<class _InIt,class _Ty>
inline_InIt _Find(_InIt _First, _InIt _Last, const _Ty& _Val)
{
// find first matching _Val
for (; _First != _Last; ++_First)
if (*_First == _Val)
break;
return (_First);
}
从实现中,可看出三个参数,开始和结束迭代器,和要查找的值_Val. 注意,find算法返回查找到的元素在容器中的位置迭代器。如果查找失败,则返回end迭代器。
void test01()
{
vector<int> v = { 1, 2, 3, 4, 5 };
vector<int>::iterator pos = find(v.begin(), v.end(), 30);
if (pos == v.end())
{
cout << "查找失败!" << endl;
return;
}
cout << "pos = " << *pos << endl;
}
如果容器中存储的非内建的数据类型,也就是自定义数据类型,我们从find算法内部实现来看,find算法是使用==号来判断元素是否相等的,所以我们必须要给自定义的对象重载==号运算符,让编译器直到如何比较两个自定义对象是否相等。
class Person
{
public:
Person(string name, int age)
{
mName = name;
mAge = age;
}
bool operator==(const Person &person)
{
return person.mName == this->mName && person.mAge == person.mAge;
}
public:
string mName;
int mAge;
};
void test02()
{
vector<int> v = { Person("aaa", 10), Person("bbb", 20), Person("ccc", 30), Person("ddd", 40)};
vector<int>::iterator pos = find(v.begin(), v.end(), Person("ccc", 30));
if (pos == v.end())
{
cout << "查找失败!" << endl;
}
else
{
cout << "查找成功!" << endl;
}
}