问题:以下代码非常具有表现力和简洁性,如果不一定快,则不是因为它不能编译.
它无法编译,因为您无法将std :: function实例与operator ==()进行比较.而std :: find()试图做到这一点.
当然,我可以采用完全不同的实现方式,但是我很顽固,因为我喜欢下面的代码,我正在寻找“尽可能接近”的东西.
谁可以为我提供一个相当重写的代码,下面的代码也做同样的事情?
- #include <functional>
- #include <vector>
- typedef std::function<bool(int)> Tester_t;
- typedef std::vector<Tester_t> TesterSet_t;
- bool Test(TesterSet_t &candidates,int foo)
- {
- TesterSet_t dropouts;
- for( auto& tester : candidates )
- {
- if(!tester(foo))
- {
- droputs.push_back(tester);
- }
- }
- while(!dropouts.empty())
- {
- // The following line is not compiling because std::function has no operator==()
- TesterSet_t::iterator culprit =
- std::find( candidates.begin(),candidates.end(),dropouts.back() );
- candidates.erase(culprit);
- dropouts.pop_back();
- }
- return !candidates.empty();
- }
解决方法
正如其他人所说,你不需要比较std :: functions.使用标准C设施,这可以有效地(线性复杂性)实现两行:
- bool Test(TesterSet_t &candidates,int foo)
- {
- candidates.erase(std::remove_if(candidates.begin(),[foo](Tester_t& f){ return !f(foo); }),candidates.end());
- return !candidates.empty();
- }