5
请用例子说明何时使用std::logical_not
和std::not1
!std :: logical_not和std :: not1之间的区别?
根据文档,前者是“一元函数对象类”,而后者是“构造一元函数对象”。因此,在一天结束时都构建一个一元函数对象,不是吗?
请用例子说明何时使用std::logical_not
和std::not1
!std :: logical_not和std :: not1之间的区别?
根据文档,前者是“一元函数对象类”,而后者是“构造一元函数对象”。因此,在一天结束时都构建一个一元函数对象,不是吗?
两者都是仿函数(与operator()
类),但是他们否定什么略有不同:
std::logical_not<T>::operator()
回报T::operator!()
。在语义上,它将T
看作是一个值并否定它。std::not1<T>::operator()
返回!(T::operator()(T::argument_type&))
。在语义上,它将T
看作谓词,并将其否定。std::not1<T>
对于更复杂的用例是std::logical_not
的推广。
请举例说明何时使用
std::logical_not
当std::not1
使用std::logical_not
只要你能。只要您的第一个选项用完,请使用std::not1
。在en.cppreference.com的例子描述了将std::not1
是必要的情况下:unary_function`已被弃用'(lambda函数只是越好):
#include <algorithm>
#include <numeric>
#include <iterator>
#include <functional>
#include <iostream>
#include <vector>
struct LessThan7 : std::unary_function<int, bool>
{
bool operator()(int i) const { return i < 7; }
};
int main()
{
std::vector<int> v(10);
std::iota(begin(v), end(v), 0);
std::cout << std::count_if(begin(v), end(v), std::not1(LessThan7())) << "\n";
//same as above, but use a lambda function
std::function<int(int)> less_than_9 = [](int x){ return x < 9; };
std::cout << std::count_if(begin(v), end(v), std::not1(less_than_9)) << "\n";
}
通知。 – edmz
事情是,lambda没有'argument_type'成员,'std :: not1'需要它。 – YSC