std::logical_not 和 std::not1 之间的区别
Difference between std::logical_not and 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
的情况:
#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";
}
相关文章:
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- std::atomic和std::condition_variable wait,notify_*方法之间的区别
- 如何使 std::sort 在 std::swap 和我的命名空间的模板化交换之间没有名称冲突?
- std::is_convertible 和 std::convertible_to 之间的区别(在实践中)?
- std::filesystem 和 std::experimental::filesystem 之间的路径差异
- 在什么条件下使用 std::memcpy 在对象之间复制是安全的?
- std::memmove在同一对象之间是否始终安全
- Cxx.jl 在 Julia Complex 和 std::complex 之间进行转换
- 如何在 std::string 和 Aws::String 之间进行转换?
- std::weak_ptr 和相应的 std::shared_ptr 之间是否存在数据竞争?
- std::fabs(a * b) 和 std::fabs(a) * std::fabs(b) 之间的区别
- 如何在窗口之间移动 std::unique_ptr 而不会冒内存泄漏的风险?
- 简单使用 std::atomic 在两个线程之间共享数据
- "+=" 操作在类型之间不起作用 std::复杂<double>和__complex__双精度
- "std::function<double(double)>"到"double (*)(double)"之间的转换
- malloc 和 calloc 与 std::string 之间的区别
- std::random_device和std::mt19937_64之间有什么区别
- 是std::memcpy在不同的可复制类型之间的未定义行为
- 我收到void main()和使用命名空间std;之间的冲突;?我正在使用代码块
- iostream和命名空间std之间的关系是什么?