C++中find_if


總結:find_if針對查找的對象中包含指針需要進行比較

           find則更偏向於普通的數值或者字符比較

            兩者都可以應用於自定義的類,只需在類中重載==運載符

函數調用符()說白了其實就是代替函數指針,調用對應重載的()的那個定義函數,()運算符只能在類中重載

 

STL的find,find_if函數提供了一種對數組、STL容器進行查找的方法。使用該函數,需包含頭文件 #include <algorithm>
我們查找一個list中的數據,通常用find(),例如:

 

那么,如果容器里的元素是一個類呢?例如,有list<CPerson> ,其中CPerson類定義如下:

class CPerson
{
public:
    CPerson(void); 
    ~CPerson(void);

public:
    int age; // 年齡
};

那么如何用find()函數進行查找呢?這時,我們需要提供一個判斷兩個CPerson對象“相等”的定義,find()函數才能從一個list中找到與指定的CPerson“相等”的元素。
這個“相等”的定義,是通過重載“==”操作符實現的,我們在CPerson類中添加一個方法,定義為:
bool operator==(const CPerson &rhs) const;
實現為:
bool CPerson::operator==(const CPerson &rhs) const
{
    return (age == rhs.age);
}

然后我們就可以這樣查找(假設list中已經有了若干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
}
這樣就實現了需求。

 

有人說,如果我有自己定義的“相等”呢?例如,有一個list<CPerson*>,這個list中的每一個元素都是一個對象的指針,我們要在這個list中查找具有指定age的元素,找到的話就   得到   對象的指針。  不只是普通需要比較類型上的相等,而是兩個對象的指針所對應的值進行比較
這時候,你不再能像上面的例子那樣做,

我們需要用到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.

 

在這順帶說明一下()的函數調用符號()的重載,它只能通過類的成員來重載

 

 

在main()函數中,cc是一個類,但是”cc();”這樣的語法卻是函數調用,在項目中這樣的寫法可以避免代碼出現函數指針

說白了,()其實就是函數指針的作用,代替了函數指針而已,在C++之后的java,就不存在指針了

 

 

我們在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函數來查找了:
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

 

引自https://blog.csdn.net/CNHK1225/article/details/48678203


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM