使用 boost.accumulators 对将特定属性设置为值的对象进行计数

Using boost.accumulators to count objects that have a certain attribute set to a value

本文关键字:对象 设置 accumulators boost 属性 使用      更新时间:2023-10-16

这是一段为我的问题设置上下文的代码(这是C++)

enum Gender { Gender_MALE, Gender_FEMALE, Gender_UNKNOWN };
enum Age { Age_CHILD, Age_ADULT, Age_SENIOR, Age_UNKNOWN };
struct Person {
  int id;
  Gender gender;
  Age age;
};
std::list<Person> people;

在填充人员列表后,我想统计列表中有多少项目属于特定性别或年龄。我知道我可以简单地遍历列表并手动计数,但我希望在某个地方可能有这种算法的更好优化版本。我读过有关提升计数累加器的信息,但我不确定是否可以在这种特定情况下使用它。

boost(或与此相关的标准库)是否提供了我可能忽略的东西,即通过属性值计算列表中的项目数?

使用 std::count_if 和合适的谓词。 例如,要查找 C++11 中ageAge_ADULTPerson对象的数量,

std::count_if(
    people.cbegin(),
    people.cend(),
    [](Person const& p){ return p.age == Age_ADULT; }
);

对于C++03,

std::count_if(
    people.begin(),
    people.end(),
    boost::bind(&Person::age, _1) == Age_ADULT
);