自定义类型的vector容器中使用find_if
今天在做题时,需要用到在一个自定义的结构体数组(实际上是vector容器)里面查找特定的值:
即:
struct good
{
int id;
int sc;
};
vector> 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 bind2nd(const Operation&op,const T&x);
其中需要注意的是,op必须是派生自binay_function:
struct compare: binary_functionstring,bool> { bool operator()( A &a, string str) const { if (a.s== str)//假设a结构体存在string变量s return true; else return false; } };
vector ::iterator f = find_if(goods[ty].begin(),goods[ty].end(),bind2nd(GT(),com));
还有一种不太理解的方法,实际使用出错了。
定义一个二元函数,利用ptr_fun函数配接器,将函数指针转换为仿函数。如下:
bool comp(good & g,int c)
{
if(g.id == c)
return true;
else
return false;
}
vector ::iterator f = find_if(goods[ty].begin(),goods[ty].end(),bind2nd(ptr_fun(comp),com));