设为首页 加入收藏

TOP

标准模板库(STL)List介绍(十)
2011-06-07 12:31:23 来源: 作者: 【 】 浏览:9187
Tags:标准 模板 STL List 介绍
 
  
使用STL通用算法find_if()在list中搜索对象  
  
  
这是find()的一个更强大的版本。这个例子演示了find_if(),它接收一个函数对象的参数作为参数, 并使用它来做更复杂的评价对象是否和给出的查找条件相付。  
假设我们的list中有一些按年代排列的包含了事件和日期的记录。我们希望找出发生在1997年的事件。  
  
/*  
|| How to find things in an STL list MkII  
*/  
#include <string>  
#include <list>  
#include <algorithm>  
   
class EventIsIn1997 {  
public:  
     bool operator () (string& EventRecord) {  
         // year field is at position 12 for 4 characters in EventRecord  
         return EventRecord.substr(12,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  
  
首页 上一页 7 8 9 10 11 12 13 下一页 尾页 10/18/18
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇 C++语言的url encode 和decode 下一篇C++ map的基本操作和使用

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: