c – 如何解决std :: function没有operator ==的事实?

前端之家收集整理的这篇文章主要介绍了c – 如何解决std :: function没有operator ==的事实?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
问题:以下代码非常具有表现力和简洁性,如果不一定快,则不是因为它不能编译.

它无法编译,因为您无法将std :: function实例与operator ==()进行比较.而std :: find()试图做到这一点.

当然,我可以采用完全不同的实现方式,但是我很顽固,因为我喜欢下面的代码,我正在寻找“尽可能接近”的东西.

谁可以为我提供一个相当重写的代码,下面的代码也做同样的事情?

  1. #include <functional>
  2. #include <vector>
  3.  
  4. typedef std::function<bool(int)> Tester_t;
  5. typedef std::vector<Tester_t> TesterSet_t;
  6.  
  7. bool Test(TesterSet_t &candidates,int foo)
  8. {
  9. TesterSet_t dropouts;
  10. for( auto& tester : candidates )
  11. {
  12. if(!tester(foo))
  13. {
  14. droputs.push_back(tester);
  15. }
  16. }
  17.  
  18. while(!dropouts.empty())
  19. {
  20. // The following line is not compiling because std::function has no operator==()
  21. TesterSet_t::iterator culprit =
  22. std::find( candidates.begin(),candidates.end(),dropouts.back() );
  23. candidates.erase(culprit);
  24. dropouts.pop_back();
  25. }
  26. return !candidates.empty();
  27. }

解决方法

正如其他人所说,你不需要比较std :: functions.使用标准C设施,这可以有效地(线性复杂性)实现两行:
  1. bool Test(TesterSet_t &candidates,int foo)
  2. {
  3. candidates.erase(std::remove_if(candidates.begin(),[foo](Tester_t& f){ return !f(foo); }),candidates.end());
  4. return !candidates.empty();
  5. }

猜你在找的C&C++相关文章