我想创建一个函数对象,将参数作为引用,而不是值。如果我使用不带std::not1的function-object,它可以工作。但是,使用std::not1时,除非参数接受参数作为值,否则根本不会编译。
下面的代码来自cppreference not1,我更改了LessThan7,将参数i作为引用,而不是值:
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";
std::function<bool(int)> less_than_9 = [](int x){ return x < 9; };
std::cout << std::count_if(begin(v), end(v), std::not1(less_than_9)) << "\n";
}为什么这段代码不能工作?
error: no matching function for call to object of type 'const LessThan7'
{return !__pred_(__x);}
^~~~~~~发布于 2021-05-17 05:59:15
传递给count_if的谓词不得修改其参数。不允许使用int &类型的参数。您应该使用const引用来获取参数:
struct LessThan7 : std::unary_function<int, bool>
{
bool operator()(const int &i) const { return i < 7; }
};https://stackoverflow.com/questions/67561847
复制相似问题