您好,登錄后才能下訂單哦!
STL的find,find_if函數(shù)提供了一種對數(shù)組、STL容器進行查找的方法。使用該函數(shù),需 #include <algorithm>
find示例一
我們查找一個list中的數(shù)據(jù),通常用find(),例如:
using namespace std; int main() { list<int> lst; lst.push_back(10); lst.push_back(20); lst.push_back(30); list<int>::iterator it = find(lst.begin(), lst.end(), 10); // 查找list中是否有元素“10” if (it != lst.end()) // 找到了 { // do something } else // 沒找到 { // do something } return 0; }
find示例二
那么,如果容器里的元素是一個類呢?例如,有l(wèi)ist<CPerson> ,其中CPerson類定義如下:
class CPerson { public: CPerson(void); ~CPerson(void); public: int age; // 年齡 };
那么如何用find()函數(shù)進行查找呢?這時,我們需要提供一個判斷兩個CPerson對象“相等”的定義,find()函數(shù)才能從一個list中找到與指定的CPerson“相等”的元素。
這個“相等”的定義,是通過重載“==”操作符實現(xiàn)的,我們在CPerson類中添加一個方法,定義為:
bool perator==(const CPerson &rhs) const; 實現(xiàn)為: bool CPerson::operator==(const CPerson &rhs) const { return (id == rhs.age); } 然后我們就可以這樣查找(假設list中已經(jīng)有了若干CPerson對象)了: list<CPerson> lst; ////////////////////////////////// // 向lst中添加元素,此處省略 ////////////////////////////////// CPerson cp_to_find; // 要查找的對象 cp_to_find.age = 50; list<CPerson>::iterator it = find(list.begin(), list.end(), cp_to_find); // 查找 if (it != lst.end()) // 找到了 { // do something } else // 沒找到 { // do something }
find_if函數(shù)示例
有人說,如果我有自己定義的“相等”呢?例如,有一個list<CPerson*>,這個list中的每一個元素都是一個對象的指針,我們要在這個list中查找具有指定age的元素,找到的話就得到對象的指針。
這時候,你不再能像上面的例子那樣做,我們需要用到find_if函數(shù),并自己指定predicate function(即find_if函數(shù)的第三個參數(shù),請查閱STL手冊)。
我們在CPerson類外部定義這樣一個結構體:
typedef struct finder_t { finder_t(int n) : age(n) { } bool operator()(CPerson *p) { return (age == p->age); } int age; }finder_t;
然后就可以利用find_if函數(shù)來查找了:
list<CPerson*> lst;//////////////////////////////////// 向lst中添加元素,此處省略//////////////////////////////////list<CPerson*>::iterator it = find_if(lst.begin(), lst.end(), finder_t(50)); // 查找年齡為50的人if (it != lst.end()) // 找到了{cout << "Found person with age : " << (*it)->age;}else // 沒找到{ // do something }
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。