根据我的理解,Functor 应该这样使用
std::greater<int> g;
std::cout << std::boolalpha << g(10, 3) << std::endl;
或作为函数的参数。
find_if(v.begin(), v.end(), std::greater<int>())
但这意味着什么?
std::cout << std::greater<int>()(100, 300) << std::endl; // output: false
当我如下使用 not_equal_to 时,它无法通过编译:
int* pt = std::adjacent_find (numbers, numbers+5, std::not_equal_to<int>(1,1)) +1;
最佳答案
Why is it working?
在第一个代码中,您在仿函数上调用operator()
,并打印出结果。
std::cout << std::greater<int>()(100, 300) << std::endl; // output: false
~~~~~~~~~~~~~~~~~~~ <- create a temporary object(functor)
~~~~~~~~~~ <- call operator() on the temporary object
Why isn't it working?
在第二段代码中,您将仿函数传递给算法,并且将通过在其上调用 operator()
来在算法内部调用仿函数。
int* pt = std::adjacent_find (numbers, numbers+5, std::not_equal_to<int>(1,1)) +1;
~~~~~~~~~~~~~~~~~~~~~~~~~~~
您正在尝试通过采用 2 个参数的构造函数创建临时 std::not_equal_to
。 std::not_equal_to
没有该 ctor,因此只需将其更改为使用默认 ctor,就像使用 std 调用
。std::find_if
所做的那样: :更大
int* pt = std::adjacent_find (numbers, numbers+5, std::not_equal_to<int>()) +1;
关于c++ - std::greater<int>()(100, 300),为什么它有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32967947/