gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:13:03 26 4
gpt4 key购买 nike

问题:如果不是因为无法编译,下面的代码虽然不一定很快,但会非常有表现力和简洁。

它无法编译,因为您无法将 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::function。使用标准的 C++ 设施,这可以在两行中有效地(具有线性复杂性)实现:

bool Test(TesterSet_t &candidates, int foo)
{
candidates.erase(std::remove_if(candidates.begin(), candidates.end(),
[foo](Tester_t& f){ return !f(foo); }), candidates.end());
return !candidates.empty();
}

关于c++ - 如何解决 std::function 没有 operator== 的事实?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28204338/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com