使用find在vector中查找成员时使用的是直接==比较,即如果vector中存放的是指针或对象时直接使用find查找将直接比较指针地址值是否相同,这时需要使用到find_if。
如有
如有
- class CAttrCheck
- {
- public:
- CString m_strCode;
- bool IsExist;
- }
有vector<CAttrCheck*> m_Attrs;
若想在m_Attrs中查找IsExist为true且m_strCode为TYPE变量值的成员,方法如下:
- struct CAttrCompare : binary_function< CAttrCheck*, CAttrCheck*, bool >
- {
- bool operator()(CAttrCheck* p1, CAttrCheck* p2) const
- {
- return (p1->m_strCode == p2->m_strCode && p1->IsExist == false);
- }
- };
- CAttrCheck* pAttrTmp = new CAttrCheck();
- pAttrTmp->m_strCode = TYPE;
- AIter = find_if(pAttrGroup->m_Attrs.begin(), pAttrGroup->m_Attrs.end(),
- bind2nd(CAttrCompare(), pAttrTmp));//AIter是vector的迭代子
因为find_if的第三个参数是个函数指针,所以比较值也就是这的TYPE值需要传进去,bind2nd可以把第2个参数传递给第1个参数(也就是struct CAttrCompare的成员函数operator()),作为函数的第二个参数。