用find if查找vector内对象的成员

               

用stl的find方法查找一个包含简单类型的vector中的元素是很简单的,例如

[cpp]  view plain copy
  1. vector<string> strVec;  find(strVec.begin(),strVec.end(),”aa”);  

假如vector包含一个复合类型的对象呢比如

[cpp]  view plain copy
  1. <pre name="code" class="cpp">class A  
  2. {  
  3. public:  
  4. A(const std::string str,int id)  
  5. {  
  6. this->str=str;  
  7. this->id=id;  
  8. }  
  9. private:  
  10. std::string str;  
  11. int id;  
  12. };</pre><br>  
  13. <pre></pre>  
  14. <pre></pre>  
  15. <pre></pre>  

这个时候一般的想法是写个函数遍历这个vector,然后进行比较查找。实际上在使用STL的时候,不建议使用循环遍历的查找方法,有几个理由(参加《effictive c++》46条):

  • 效率:泛型算法通常比循环高效。
  • 正确性: 写循环时比调用泛型算法更容易产生错误。
  • 可维护性: 与相应的显式循环相比,泛型算法通常使代码更干净、更直观。

实际上通过find_if泛型算法可以很优雅的达到期望的效果。template<class InputIterator, class Predicate> InputIterator find_if( InputIterator _First, InputIterator _Last, Predicate_Pred );这里的最后一个参数可是一个一元谓词,即只带一个参数且返回值限定为bool的函数对象,例如

[cpp]  view plain copy
  1. bool compare(A& dValue)  
  2. {  
  3. if(dValue.GetStr().compare(“bb”)==0)  
  4. return true;  
  5. else  
  6. return false;  
  7. }  


示例:

[cpp]  view plain copy
  1. vector<A> a;  
  2. A b(“aa”,4);  
  3. A c(“bb”,6);  
  4. A d(“zz”,7);  
  5. a.push_back(b);  
  6. a.push_back(c);  
  7. a.push_back(d);  
  8. vector<A>::iterator t=find_if(a.begin(),a.end(),compare);  


以上函数限定了比较的内容,如果我们想要灵活的自定义比较条件的话要如何做呢,有2个办法,一个是自定义类
,并重载()操作符号,例如:

[cpp]  view plain copy
  1. class findx  
  2. {  
  3. public:  
  4. findx(const string str)  
  5. {  
  6. class D  
  7. {};  
  8. test=str;  
  9. }  
  10. string GetTest()  
  11. {  
  12. return test;  
  13. }  
  14. bool operator()(A& dValue)  
  15. {  
  16. if(dValue.GetStr().compare(test)==0)  
  17. return true;  
  18. else  
  19. return false;  
  20. }  
  21. private:  
  22. string test;  
  23. };  

比较的时候只要

[cpp]  view plain copy
  1. vector<A>::iterator t=find_if(a.begin(),a.end(),findx(“33″));  

还有一种方法是使用仿函数和绑定器。仿函数就是类似上面的重载了操作符()的自定义类,或者用struct也可以。因为他定义了操作符“()”,所以能够像函数调用一样在对象名后加上“()”,并传入对应的参数,从而执行相应的功能。这样的类型就是函数对象,从而能作为函数参数传递给find_if。

下面再说绑定器:STL中的绑定器有类绑定器和函数绑定器两种,类绑定器有binder1st和binder2nd,而函数绑定器是bind1st和bind2nd,他们的基本目的都是用于构造一个一元的函数对象。比如这里我们可以利用bind2nd通过绑定二元函数对象中的第二个参数的方式来实现二元谓词向一元谓词的转换。

[cpp]  view plain copy
  1. struct compare: binary_function<A, string,bool>  
  2. {  
  3. bool operator()( A &value, string str) const  
  4. {  
  5. if (value.GetStr()== str)  
  6. return true;  
  7. else  
  8. return false;  
  9. }  
  10. };  

示例:

[cpp]  view plain copy
  1. vector<A>::iterator t=find_if(a.begin(),a.end(),bind2nd(compare(),”33″));  

无论是用vector的循环还是find_if泛型算法,在性能和代码复杂度上面都有一定得权衡,至于在实际应用中,还是需要具体问题具体分析的

           

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

猜你喜欢

转载自blog.csdn.net/yrryyff/article/details/86536034