STL的find,find_if函数提供了一种对数组、STL容器进行查找的方法。使用该函数,需 #include
我们查找一个list中的数据,通常用find(),例如:
using namespace std;
int main()
{
list
lst.push_back(10);
lst.push_back(20);
lst.push_back(30);
list
if (it != lst.end()) // 找到了
{
// do something
}
else // 没找到
{
// do something
}
return 0;
}
那么,如果容器里的元素是一个类呢?例如,有list
class CPerson
{
public:
CPerson(void); ~CPerson(void);
public:
int age; // 年龄
};
那么如何用find()函数进行查找呢?这时,我们需要提供一个判断两个CPerson对象“相等”的定义,find()函数才能从一个list中找到与指定的CPerson“相等”的元素。
这个“相等”的定义,是通过重载“==”操作符实现的,我们在CPerson类中添加一个方法,定义为:
bool operator==(const CPerson &rhs) const;
实现为:
bool CPerson::operator==(const CPerson &rhs) const
{
return (id == rhs.age);
}
if (it != lst.end()) // 找到了
{
// do something
}
else // 没找到
{
// do something
}
这样就实现了需求。
有人说,如果我有自己定义的“相等”呢?例如,有一个list
这时候,你不再能像上面的例子那样做,我们需要用到find_if函数,并自己指定predicate function(即find_if函数的第三个参数,请查阅STL手册)。先看看find_if函数的定义:
templateInputIterator find_if(InputIterator _First, InputIterator _Last, Predicate _Pred);
An input iterator addressing the position of the first element in the range to be searched.
An input iterator addressing the position one past the final element in the range to be searched.
User-defined predicate function object that defines the condition to be satisfied by the element being searched for. A predicate takes single argument and returns true or false.
if (it != lst.end()) // 找到了
{
cout << "Found person with age : " << (*it)->age;
}
else // 没找到
{
// do something
}