版权声明:本文为博主原创文章,未经博主允许不得转载。
上一篇文章也讲过,find()函数只能处理简单类型的内容,也就是缺省类型,如果你想用一个自定义类型的数据作为查找依据则会出错!这里将讲述另外一个函数find_if()的用法
这是find()的一个更强大的版本。这个例子演示了find_if(),它接收一个函数对象的参数作为参数, 并使用它来做更复杂的评价对象是否和给出的查找条件相付。
假设我们的list中有一些按年代排列的包含了事件和日期的记录。我们希望找出发生在1997年的事件。
代码如下:
- //----------------------------------------------------------------------------------------
- // Desc: STL_find_if()_How to find things in an STL list MkII
- // Author: pigfly
- // Data: 2010.12.01
- // Copyright (C) 2010 pigfly
- //----------------------------------------------------------------------------------------
- #include <iostream>
- #include <string>
- #include <list>
- #include <algorithm>
- using namespace std;
- class EventIsIn1997 {
- public:
- bool operator () (string& EventRecord) {
- // year field is at position 12 for 4 characters in EventRecord
- return EventRecord.substr(11,4)=="1997";
- //return this->substr(11,4)=="1997"
- }
- };
- int main (void) {
- list<string> Events;
- // string positions 0123456789012345678901234567890123456789012345
- Events.push_back("07 January 1995 Draft plan of house prepared");
- Events.push_back("07 February 1996 Detailed plan of house prepared");
- Events.push_back("10 January 1997 Client agrees to job");
- Events.push_back("15 January 1997 Builder starts work on bedroom");
- Events.push_back("30 April 1997 Builder finishes work");
- list<string>::iterator EventIterator = find_if (Events.begin(), Events.end(), EventIsIn1997());
- // find_if completes the first time EventIsIn1997()() returns true
- // for any object. It returns an iterator to that object which we
- // can dereference to get the object, or if EventIsIn1997()() never
- // returned true, find_if returns end()
- if (EventIterator==Events.end()) {
- cout << "Event not found in list" << endl;
- }
- else {
- cout << *EventIterator << endl;
- }
- }
输出:
10 January 1997 Client agrees to job
这里请注意,find_if()的第三个参数是EventIsIn1997(),它是个仿函数,接收一个string对象,在运算符()的内部定义我所要的查找条件,本例的查找条件是:EventRecord.substr(11,4)=="1997",注意,这里的仿函数返回类型必须是bool类型,这客观反应在find_if()函数查找过程中的是否匹配!
下面我们在看看,数据类型是自定义的结构体的查找过程:
代码: