count_if使用我自己的类实现第三个参数

count_if third argument implementation using my own class

本文关键字:参数 三个 实现 if 自己的 我自己 count      更新时间:2023-10-16

我在编写函数以正确将参数传递给算法库count_if时遇到问题。

这是我的代码。

int range = count_if(empVect.begin(), empVect.end(), empVect.InRange(200,399));

范围函数实现为:

bool Employee::inRange(double min, double max)
{
if (nIncome > min && nIncome < max)
return true;
return false;
}

编译器错误:类"std::vector>"没有成员"InRange"

我有一个包含 2 个字符串和 3 个双成员变量的 Employee 类。我已经在我的主中创建对矢量创建进行了硬编码,并且需要显示一定收入范围内的员工数量。根据分配要求,仅需要使用 count_if 或 lambda 函数。谢谢。

empVect是一个std::vector<Employee>,它没有接受任何东西的InRange成员函数。该函数是 Employee 类的成员。您需要定义一个函子,该函子将使用您传递的参数在向量的每个实例上调用该成员。一个简单的lambda就可以了:

int range = count_if(empVect.begin(), empVect.end(), [](Employee const& e){
               return e.InRange(200,399);
            });

您还需要将inRange修复为 const 成员函数,因为e是对 const Employee 的引用。渴望编写常量正确的代码。如果成员未修改任何成员数据,则默认将其标记为 const。