STL中的find_if函数
生活随笔
收集整理的這篇文章主要介紹了
STL中的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 EventRecordreturn EventRecord.substr(11,4)=="1997";//return this->substr(11,4)=="1997"} };int main (void) {list<string> Events;// string positions 0123456789012345678901234567890123456789012345Events.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()函數查找過程中的是否匹配!
=========================================
注意一下,上面的find_if沒有參數,來個帶參數的例子,貼出關鍵代碼,
std::list<ClientItem*> m_pclientitemlist; //客戶端列表 class EventIfExistSock { public:EventIfExistSock(const int pdevid) :m_devid(pdevid){}bool operator () (ClientItem* pci){return pci->clientid == m_devid;} private:int m_devid; };std::list<ClientItem*>::iterator sockitemiter = find_if(m_pclientitemlist.begin(), m_pclientitemlist.end(), EventIfExistSock(1001)); bool online = iter != DeviceManager::GetInstance()->GetDeviceList().end() ? true : false;
總結
以上是生活随笔為你收集整理的STL中的find_if函数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: HOOK汇总
- 下一篇: mysql_ping与mysql长连接