使用boost.accumulators计算具有某个属性设置为值的对象

Fre*_*red 1 c++ boost stl accumulator

这是一段代码,为我的问题设置了上下文(这是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;
Run Code Online (Sandbox Code Playgroud)

在填写人员列表后,我想获得列表中有多少项具有特定性别或年龄的记录.我知道我可以简单地遍历列表并手动计数,但我希望在某处可能有更好的优化版本的这种算法.我读到了有关boost计数累加器的信息,但我不确定在这种情况下我是否可以使用它.

boost(或标准库)提供了一些我可能忽略的东西,通过属性的值来计算列表中的项目数量?

ild*_*arn 7

使用std :: count_if和合适的谓词.例如,找到的数目Person的对象与ageAge_ADULT在C++ 11,

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

对于C++ 03,

std::count_if(
    people.begin(),
    people.end(),
    boost::bind(&Person::age, _1) == Age_ADULT
);
Run Code Online (Sandbox Code Playgroud)