stl find和find_if
2012-11-22 11:06
197 查看
STL的find,find_if函数提供了一种对数组、STL容器进行查找的方法。使用该函数,需 #include <algorithm>
我们查找一个list中的数据,通常用find(),例如:
文章来源:http://www.codelast.com/
那么,如果容器里的元素是一个类呢?例如,有list<CPerson> ,其中CPerson类定义如下:
那么如何用find()函数进行查找呢?这时,我们需要提供一个判断两个CPerson对象“相等”的定义,find()函数才能从一个list中找到与指定的CPerson“相等”的元素。
文章来源:http://www.codelast.com/
这个“相等”的定义,是通过重载“==”操作符实现的,我们在CPerson类中添加一个方法,定义为:
实现为:
然后我们就可以这样查找(假设list中已经有了若干CPerson对象)了:
这样就实现了需求。
有人说,如果我有自己定义的“相等”呢?例如,有一个list<CPerson*>,这个list中的每一个元素都是一个对象的指针,我们要在这个list中查找具有指定age的元素,找到的话就得到对象的指针。
文章来源:http://www.codelast.com/
这时候,你不再能像上面的例子那样做,我们需要用到find_if函数,并自己指定predicate function(即find_if函数的第三个参数,请查阅STL手册)。先看看find_if函数的定义:
template<class InputIterator, class Predicate>
InputIterator find_if(InputIterator _First, InputIterator _Last, Predicate _Pred);
Parameters
_First
An input iterator addressing the position of the first element in the range
to be searched.
_Last
An input iterator addressing the position one past the final element in the
range to be searched.
_Pred
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.
我们在CPerson类外部定义这样一个结构体:
然后就可以利用find_if函数来查找了:
我们查找一个list中的数据,通常用find(),例如:
文章来源:http://www.codelast.com/
文章来源:http://www.codelast.com/
这个“相等”的定义,是通过重载“==”操作符实现的,我们在CPerson类中添加一个方法,定义为:
有人说,如果我有自己定义的“相等”呢?例如,有一个list<CPerson*>,这个list中的每一个元素都是一个对象的指针,我们要在这个list中查找具有指定age的元素,找到的话就得到对象的指针。
文章来源:http://www.codelast.com/
这时候,你不再能像上面的例子那样做,我们需要用到find_if函数,并自己指定predicate function(即find_if函数的第三个参数,请查阅STL手册)。先看看find_if函数的定义:
template<class InputIterator, class Predicate>
InputIterator find_if(InputIterator _First, InputIterator _Last, Predicate _Pred);
Parameters
_First
An input iterator addressing the position of the first element in the range
to be searched.
_Last
An input iterator addressing the position one past the final element in the
range to be searched.
_Pred
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.
我们在CPerson类外部定义这样一个结构体:
相关文章推荐
- STL应用 vector & find_if
- STL之for_each, find_if,adjacent_find,count_if的使用
- STL find_if使用(exam)
- STL算法find,find_if,find_if_not,sort,fill,for_each,count,adjacent_find,random_shuffle,prev_permutation
- 【C++ STL学习之七】STL算法之find和find_if
- STL之vector,数组线性容器array,list容器,算法find,find_if,bind1st,仿函数
- STL algorithm find_if
- STL之for_each, cout, cout_if, find, find_if
- STL_算法_查找算法(find、find_if)
- STL 算法Find_if_not+匿名函数
- STL算法find_if和find
- STL: bind1st, find_if
- c++ stl algorithm: std::find, std::find_if
- 从零开始学C++之STL(五):非变动性算法源代码分析与使用示例( for_each、min_element 、find_if、search 等)
- STL find_if
- STL 查找vector容器中的指定对象:find()与find_if()算法
- c++ stl algorithm: std::find, std::find_if
- stl.find_if用法总结
- STL中vector查找算法find()和find_if()深入比较
- STL 之find,find_if,find_end,find_first_of