1

这是为我的问题设置上下文的代码片段(这是 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(或与此相关的标准库)是否提供了一些我可能忽略的东西来通过属性的值来计算列表中的项目数?

4

1 回答 1

7

使用std::count_if和合适的谓词。例如,要在 C++11 中查找具有of的Person对象的数量,ageAge_ADULT

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
);
于 2011-05-19T17:29:37.233 回答