天天看點

自定義類型的vector容器中使用find_if

今天在做題時,需要用到在一個自定義的結構體數組(實際上是vector容器)裡面查找特定的值:

即:

struct good
{
    int id;
    int sc;
};      
vector<vector<good>> goods;      

在goods中查找  id == 特定值  的good。

由于習慣使用vector和不想周遊(懶得寫代碼),想要使用find_if函數。可是。。。平時用到的并沒有這麼複雜的搜尋,find_if函數基本的用法并不支援。

template<class InputIterator, class Predicate> InputIterator find_if( InputIterator _First, InputIterator _Last, Predicate_Pred );      

最後一個參數可是一個一進制謂詞,即隻帶一個參數且傳回值限定為bool的函數對象。

也就是:(舉個栗子)

bool comp(good & g)
{
    if(g.id == 0)
        return true;
    else
        return false;
}      

但此處一個參數明顯不能完成需求,

查閱學習之,可以使用bind2nd()實作二進制謂詞向一進制謂詞的轉換,bind2nd是一個函數綁定器。

STL中的綁定器有類綁定器和函數綁定器兩種,類綁定器有binder1st和binder2nd,而函數綁定器是bind1st和bind2nd,他們的基本目的都是用于構造一個一進制的函數對象。

在此不做具體展開,感興趣可以自行查閱。

template <class Operation,class T>
  binder2nd <Operation> bind2nd(const Operation&op,const T&x);      

其中需要注意的是,op必須是派生自binay_function:

struct compare: binary_function<A, string,bool> {

             bool operator()( A &a, string str) const

             {

                    if (a.s== str)//假設a結構體存在string變量s

                           return true;

                   else

                           return false;

              }

};      
vector<good> ::iterator  f = find_if(goods[ty].begin(),goods[ty].end(),bind2nd(GT(),com));      

還有一種不太了解的方法,實際使用出錯了。

bool comp(good & g,int c)
{
    if(g.id == c)
        return true;
    else
        return false;
}
vector<good> ::iterator  f = find_if(goods[ty].begin(),goods[ty].end(),bind2nd(ptr_fun(comp),com));