对于通用算法,我们可以使用 std::bind
来提供谓词。
我们如何否定该谓词?
例如,考虑一个程序,该程序在 vector
中找到第一个可以被 3 整除的元素。
bool is_divisible(int m, int n)
{
return m % n == 0;
}
int main()
{
vector<int> v = { 3, 6, 9, 11, 15 };
int n = 3;
auto it = find_if(v.cbegin(), v.cend(), bind(is_divisible, _1, n));
return 0;
}
现在我想通过否定 bind
提供的谓词来找到 不能被 3 整除 的第一个元素。我该怎么做?
我试过了
auto it = find_if(v.cbegin(), v.cend(), not1(bind(is_divisible, _1, n)));
产生以下错误
error: no type named 'argument_type' in
'struct std::_Bind<bool(*(std::_Placeholder<1>, int))(int, int)>' class unary_negate
请不要建议使用 lambda 或 find_if_not
,这不是本题的目的。
非常感谢!
最佳答案
既然你喜欢bind
,就再bind
一些:
find_if(v.cbegin(), v.cend(), std::bind(std::logical_not<bool>(),
std::bind(is_divisible, _1, n)));
(当然,如果您可以访问 C++17 not_fn
,您可以直接使用它。)
关于c++ - 如何否定 `std::bind` 提供的谓词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48922850/